使用 PowerShell 加载 XML 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3935395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:20:45  来源:igfitidea点击:

Loading XML string with PowerShell

xmlpowershell

提问by rickythefox

I have defined an XML string using

我已经使用定义了一个 XML 字符串

$str = "<a><b></b></a>"

Now I want to load it into a [xml] variable to be able to manipulate it's nodes etc. The row below results in an error...

现在我想将它加载到 [xml] 变量中,以便能够操作它的节点等。下面的行会导致错误...

$str = [xml]"<a><b></b></a>"

How do I do this?

我该怎么做呢?

回答by Urda

The code in your question seems to work for me. I just added testinside my string to show I can access the value, but it should work without it, too.

您问题中的代码似乎对我有用。我只是test在我的字符串中添加以显示我可以访问该值,但它也应该在没有它的情况下工作。

Yes I added test, but you can see my example workedFull Image

是的,我添加了测试,但是您可以看到我的示例有效完整图像

Casting a string also worked for me:

铸造一个字符串也对我有用:

Again, I added test to show that I can access XML membersFull Image

同样,我添加了测试以表明我可以访问 XML 成员完整图像



...and I ran it with your string and it worked fine... ...notice there was an empty return?Full Image

...我用你的字符串运行它,它工作正常...... ...notice there was an empty return?完整图片

回答by Awadhesh Verma

Try this

尝试这个

$xmlcontent = variable which holds xml data in string
$xml = New-Object -TypeName System.Xml.XmlDocument
$xml.LoadXml($xmlcontent)

回答by HockeyJ

For the benefit of searchers, if you have a top line of xml that includes formatting (rather than straight in at the root node) info you need to remove the top line before you can cast it

为了搜索者的利益,如果您的 xml 顶行包含格式(而不是直接在根节点中)信息,则需要先删除顶行,然后才能进行转换

e.g.

例如

<?xml version="1.0" encoding="utf-8"?>
<Courses>
  <CourseEntry Type="Mandatory" Name="Math"/>
  <CourseEntry Type="Mandatory" Name="Coding" />
  <CourseEntry Type="Optional" Name="Economics" />
  <CourseEntry Type="Optional" Name="History" />
</Courses>

Requires:

要求:

$xmlFile = Get-Content "*.xml"
$xmlFileMinusFormatData = $xmlFile[1..($xmlFile.Length - 1)] #we need to remove the first line
$usableXml = [xml]$xmlFileMinusFormatData # Convert to xml for easy handling
$usableXml.Courses.CourseEntry.Count # just a count of rows