elbarto99se
elbarto99se

Reputation: 41

Create root element, then create comment in root using CreateComment

I am trying to create an XML object in PowerShell 2.0 with just a root element and a comment inside the root element.

I can't seem to get the CreateComment() to work.

Below is what I have tried:

# Set env current directory to the same
# as pwd so file is save in pwd
# instead of saving to where the "Start in"
# field in the shortcut to powershell.exe"
# is pointing to
[Environment]::CurrentDirectory = $pwd

# Add a 1st comment inside <root> tag
$root = $xml.root
$com = $xml.CreateComment($root)
$com.InnerText = ' my 1st comment '

# This causes an error
#$xml.root.AppendComment($com)
#Method invocation failed because [System.String] doesn't contain a method named 'AppendComment'.
#At line:1 char:24
#+ $xml.root.AppendComment <<<< ($com)
#    + CategoryInfo          : InvalidOperation: (AppendComment:String) [], RuntimeException
#    + FullyQualifiedErrorId : MethodNotFound

# This doesn't have the <!-- ... --> part of the comment tag
# it has &lt;-- ... --&gt; instead
$xml.root = $com.OuterXml

$xml.Save(".\jj.xml")

What I want in jj.xml:

<root><!-- my 1st comment --></root>

What I get:

<root>&lt;!-- my 1st comment --&gt;</root>
<!-- my 1st comment -->

Is there a way to add the $com inside the <root> </root> element and use CreateComment()?

Upvotes: 1

Views: 2075

Answers (2)

elbarto99se
elbarto99se

Reputation: 41

Thanks Brian: I added your code to the original so it works. I also added the "Create the root element" that I forgot in the original question.

# Set env current directory to the same
# as pwd so file is save in pwd
# instead of saving to where the "Start in"
# field in the shortcut to powershell.exe"
# is pointing to
[Environment]::CurrentDirectory = $pwd

# Create the root element
$xml = New-Object XML
$el = $xml.CreateElement("root")
$xml.AppendChild($el)

# Add a 1st comment inside <root> tag
$com = $xml.CreateComment(' my 1st comment ')
$xml.DocumentElement.AppendChild($com)

$xml.Save(".\jj.xml")

#What I get :)
#----jj.xml----
#<root>
#  <!-- my 1st comment -->
#</root>
#--------------

Upvotes: 0

briantist
briantist

Reputation: 47832

This worked for me:

$x = [xml]'<root></root>'
$c = $x.CreateComment('my comment')
$x.DocumentElement.AppendChild($c)
$x.InnerXml

# Output
# <root><!--my comment--></root>

Upvotes: 1

Related Questions