xml - 从字符串(不是文件)获取 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 的正确方法是什么?
解决方案
您可以直接将字符串转换为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
.
推荐阅读
- groovy - 如何在 JMeter 中设置 cookieJar
- angular - 在Angular中将HTML转换为PDF时如何格式化PDF
- salesforce - 如何在 Apex 中使用嵌套三元运算符
- javascript - Clipboard.JS 如何使用“成功”事件将新字符串置于前面?
- typescript - 解构泛型类型
- windows - 基于单个值命名 reg 文件
- flutter - 在 Flutter 的超类型中,“build”方法始终是抽象的
- c# - AutoMapper,反向映射不适用于嵌入式对象?
- django - 使用 PGPOOL-II 运行 Django + Guardian 时出现随机 NoneType 异常
- python - LSTM RNN 预测的反向缩放输出错误