Jay
Jay

Reputation: 2703

Why is OuterXml not producing a string value after modifying XML

I have the below Powershell code where, when executed, the $b4 has a string value, but once I modify the DOM in any way and try to access XmlDocument properties, such as OuterXml, I get no value in $after.

I believe this is some type of casting issue but, I cannot determine the cause.

$xml = [xml]"<root></root>"
$comment = $xml.CreateComment("<!-- added from comment -->" )
$b4 = $xml.OuterXml #this has a value as expected
$xml.FirstChild.AppendChild($comment)
$after = $xml.OuterXml  #This is empty string or null

How can I get the OuterXml value of $xml after modifying the DOM?

Upvotes: 0

Views: 1952

Answers (1)

Syphirint
Syphirint

Reputation: 1131

From what I understood, you just need to remove <!-- and --> when creating the comment. Like this:

$xml = [xml]"<root></root>"

$comment = $xml.CreateComment("added from comment") #From here
$b4 = $xml.OuterXml #this has a value as expected

$xml.FirstChild.AppendChild($comment)
$after = $xml.OuterXml  #Not null

Upvotes: 1

Related Questions