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

时间:2019-01-11 11:00:38

标签: 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)

$content的值为null

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

我检查了字符串是否以[System.Text.Encoding]::UTF8.GetPreamble()开头,但不是。

请问,将这种字符串转换为XML的正确方法是什么?

2 个答案:

答案 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