Search notes:

System.Xml.XmlDocument (class)

System.Xml.XmlDocument derives from System.Xml.XmlNode and represents an XML document in memory.

Methods

CloneNode duplicates a node
CreateAttribute Creates a System.Xml.XmlAttribute with the given name
CreateCDataSection Creates a System.Xml.XmlCDataSection with the given data
CreateComment Creates a System.Xml.XmlComment
CreateDefaultAttribute Creates a System.Xml.XmlDocumentFragment
CreateDocumentFragment
CreateDocumentType Creates a System.Xml.XmlDocumentType instance
CreateElement Creates a System.Xml.XmlElement instance
CreateEntityReference
CreateNavigator Creates a System.Xml.XPath.XPathNavigator instance to navigate this document.
CreateNode Creates a System.Xml.XmlNode instance
CreateProcessingInstruction
CreateSignificantWhitespace
CreateTextNode Creates a System.Xml.XmlTextNode instance
CreateWhitespace
CreateXmlDeclaration
GetElementById
GetElementsByTagName
ImportNode
Load
LoadXml
ReadNode
Save Format an XML document and save it
Validate
WriteContentTo
WriteTo
See also the methods of the base class XmlNode.

Example: modify an XML document

The following simple PowerShell script tries to demonstrate how an XML document can be modifed using System.Xml.XmlDocument:
set-strictMode -version latest

function get-or-create-elem-with-id($doc, $id) {

   $elem = $doc.SelectSingleNode("/rt/item[@id='$id']")

   if ($elem -eq $null) {
      $elem = $doc.CreateElement('elem')
      $elem.SetAttribute('id', $id)

      $null = $doc.SelectSingleNode('/rt').AppendChild($elem)
   }

   return $elem
}


function create-val-if-not-exists($elem, $valName, $doc) {

   if ($elem.SelectSingleNode($valName) -eq $null) {

      $val = $doc.CreateElement($valName)
      $val.InnerText = 'created'

      $null = $elem.AppendChild($val)
   }
}


[xml] $doc = new-object xml
$doc.Load("$pwd/orig.xml")

foreach ($id in 'foo', 'bar', 'baz') {

   $elem = get-or-create-elem-with-id $doc  $id

   create-val-if-not-exists $elem 'valOne' $doc
   create-val-if-not-exists $elem 'valTwo' $doc
}

$doc.Save("$pwd/modified.xml")
type modified.xml
Github repository .NET-API, path: /System/Xml/XmlDocument/_modify/modify.ps1

orig.xml

This is the orig.xml file that is modified by the script:
<rt>

   <item id="foo">
      <valOne>foo 1</valOne>
      <valTwo>foo 2</valTwo>
   </item>

   <item id="baz">
      <valOne>baz 1</valOne>
   </item>

</rt>

modified.xml

The result of running the script is:
<rt>
  <item id="foo">
    <valOne>foo 1</valOne>
    <valTwo>foo 2</valTwo>
  </item>
  <item id="baz">
    <valOne>baz 1</valOne>
    <valTwo>created</valTwo>
  </item>
  <elem id="bar">
    <valOne>created</valOne>
    <valTwo>created</valTwo>
  </elem>
</rt>

See also

The PowerShell type accelerator for System.Xml.XmlDocument is [xml].

Index