我有一个 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 的正确方法是什么?
最佳答案
您可以像这样直接将字符串转换为 XmlDocument
:
[xml]$xmlString="<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
如果你想保持变量的格式,你可以这样做:
$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
。
关于xml - 从字符串(不是文件)获取 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54145194/