我试图在PowerShell 2.0中只使用根元素创建一个XML对象 和根元素内的注释。
我似乎无法让CreateComment()
工作。
以下是我的尝试:
# 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 <-- ... --> instead
$xml.root = $com.OuterXml
$xml.Save(".\jj.xml")
我想要jj.xml
:
<root><!-- my 1st comment --></root>
我得到了什么:
<root><!-- my 1st comment --></root>
<!-- my 1st comment -->
有没有办法在$com
元素中添加<root> </root>
并使用CreateComment()
?
答案 0 :(得分:1)
这对我有用:
$x = [xml]'<root></root>'
$c = $x.CreateComment('my comment')
$x.DocumentElement.AppendChild($c)
$x.InnerXml
# Output
# <root><!--my comment--></root>
答案 1 :(得分:0)
谢谢Brian: 我将您的代码添加到原始代码中以便它可以正常工 我还添加了&#34;创建根元素&#34;那 我忘记了原来的问题。
# 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>
#--------------
&#13;