简体   繁体   中英

PowerShell set_InnerXML on node

I'm working with PowerShell to manipulate some XML and I've managed to get set_InnerXML("contents") working when creating Elements that are being added to the DOM but I've having difficulty adding a string of nodes to a node in the DOM.

Working example when creating element

$xml = New-Object XML
$xml.Load(".\file.xml")
$newnode= $xml.CreateElement("newelament")
$newnode.set_InnerXML("<stringnode>content</stringnode>")
$root = $xml.get_DocumentElement()
$result = $root.InsertAfter($newnode, $root.get_FirstChild())
$xml.Save(".\file.xml")

Not working example with existing nodes

$xml = New-Object XML
$xml.Load(".\file.xml")
$xml.node1.node2.set_InnerXML("<stringnode>content</stringnode>")
$xml.Save(".\file.xml")

Any sugestions on how to do this would be appreciated.

PS> $xml = [xml](Get-Content ~\foo.xml)
PS> $xml | Format-Xml
<root>
  <book>
    <chapter1 />
    <chapter2 />
  </book>
</root>

Update : the use of InnerXml/InnerText properties modify the content of a node but don't seem to modify the DOM to add the new elements as XmlNodes. For creation of new nodes that can be manipulated using the DOM, use the appropriate XmlDocument Create methods eg:

$book = $xml.root.book
$xml.root.book.RemoveAll()
$book -eq $xml.root.book

$intro = $xml.CreateElement("Intro")
$book.AppendChild($intro) > $null

$para = $xml.CreateElement("Para")
$intro.AppendChild($para) > $null
$xml | Format-Xml

Note: Format-Xml is a cmdlet from the PowerShell Community Extensions .

Also note that I capture the $book xml node because after you execute RemoveAll() all on it, PowerShell no longer consider book an XmlNode but a string instead. Seems like a case of the Xml adapter being too cute for its own good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM