从字符串(不是文件)获取 XML

Dis*_*ple 3 xml string powershell

我有一个 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)
Run Code Online (Sandbox Code Playgroud)

$content值为null

$xml变量的内部异常是<Error retrieving property - ArgumentException>

我已经检查过字符串是否以 开头,[System.Text.Encoding]::UTF8.GetPreamble()但没有。

您能告诉我将此类字符串转换为 XML 的正确方法是什么吗?

Pax*_*axz 5

你可以直接将字符串转换XmlDocument成这样:

[xml]$xmlString="<root>
        <section>
            <node id='1'>AAA</node>
            <node id='2'>BBB</node>
            <node id='3'>CCC</node>
        </section>
    </root>"
Run Code Online (Sandbox Code Playgroud)

如果你想保留变量的格式,你可以像这样:

$xmlString="<root>
        <section>
            <node id='1'>AAA</node>
            <node id='2'>BBB</node>
            <node id='3'>CCC</node>
        </section>
    </root>"

[xml]$content = $xmlString
Run Code Online (Sandbox Code Playgroud)

要跟进@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)
Run Code Online (Sandbox Code Playgroud)

LoadXml将给定字符串中的值加载到$xml调用该方法的变量中。

它不返回任何值,而是将其保存到$xml.