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

标签 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 的正确方法是什么?

最佳答案

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

相关文章:

powershell - 在PowerShell中获取PATH环境变量

windows - MS Windows 自动化并记录从 Ctrl-Alt-Delete 屏幕到开始菜单所需的时间

java - 查找并替换 xml 文件中的 int

php - Magento 中仍在使用数据库布局更新吗?

带冒号的 Java SPLIT : and xml

c# - 在新行中打印字符串 (C#)

string - 使用矩阵代数来操作字符串: is it feasible?

string - Golang 递增字符串中的数字(使用 rune )

c# - 在 C# .NET 项目中启动时如何等待提升的 PowerShell 进程退出?

android - 当按钮具有波纹效果时,在按钮属性中更改按钮(出现)的颜色