我有一个PowerShell脚本:
$xmlString="<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
$xml = New-Object -TypeName System.Xml.XmlDocument
$content = $xml.LoadXml($xmlString)
$content
的值为null
$xml
变量中的内部异常为<Error retrieving property - ArgumentException>
我检查了字符串是否以[System.Text.Encoding]::UTF8.GetPreamble()
开头,但不是。
请问,将这种字符串转换为XML的正确方法是什么?
答案 0 :(得分:4)
您可以像这样直接将字符串转换为XmlDocument
:
[xml]$xmlString="<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
如果要保留变量的格式,可以像这样:ofc:
$xmlString="<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
[xml]$content = $xmlString
要跟进@AnsgarWiechers的评论,如果您真的想使用LoadXML
,它应该是这样:
$xmlString=
"<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
$xml = New-Object -TypeName System.Xml.XmlDocument
$xml.LoadXml($xmlString)
LoadXml
将给定字符串中的值加载到调用方法的$xml
变量中。
它不返回任何值,但将其保存到$xml
。
答案 1 :(得分:1)
ConvertFrom-Xml
是您所需要的!
可从PowerShell库中作为Avande.CoolFunctions的一部分获得
$xmlString = @"
<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>
"@
$xmlString | ConvertFrom-Xml