首页 > 解决方案 > 从字符串(不是文件)获取 XML

问题描述

我有一个 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 的正确方法是什么?

标签: xmlstringpowershell

解决方案


您可以直接将字符串转换为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.


推荐阅读