【问题标题】:Powershell - Looping through XMLPowershell - 通过 XML 循环
【发布时间】:2018-06-18 22:24:52
【问题描述】:

我已经制作了这个示例 XML 来循环遍历,我有兴趣为每个项目输出产品名称。

<example>
<item>
    <productname>Hoover</productname>
</item>
<item>
    <productname>TV</productname>
</item>
<item>
    <productname>Microwave</productname>
</item>
<item>
    <productname>Computer</productname>
</item>
</example>

在我的 powershell 中,我可以轻松地遍历每个项目,但我无法选择“产品名称”的内容,我不确定为什么。这是我的示例 powershell 代码:

[xml] $xml = Get-Content "./xmlexample.xml"

foreach ($item in $xml.example) {
    Write-Host($item.InnerXML) #Outputs all XML as expected
    Write-Host($item.InnerText) #Outputs the text of all child elements as expected 
    Write-Host($item.productname.InnerText) #Does not output anything
    Write-Host($item.productname.InnerXML) #Does not output anything
}

任何关于为什么这不起作用的帮助或建议将不胜感激。它的行为就像一个没有其他子元素的子元素不会被以同样的方式对待。

【问题讨论】:

  • 请尝试foreach ($item in $xml.example.ChildNodes)

标签: xml powershell


【解决方案1】:

遍历$xml.example.ChildNodes,然后文本就是$item.productname

PS C:\users\IEUser\Documents> foreach ($item in $xml.example.ChildNodes) {
>>>    Write-Host($item.productname)
>>> }
Hoover
TV
Microwave
Computer

或者,如果您只想要包含 productnameitem 元素,您可以迭代 item 节点:

PS C:\users\IEUser\Documents> foreach ($item in $xml.example.item) {
>>>    Write-Host($item.productname)
>>> }
Hoover
TV
Microwave
Computer

或者直接提取一个字符串数组:

PS C:\users\IEUser\Documents> $xml.example.item.productname
Hoover
TV
Microwave
Computer

【讨论】:

  • 也许你在$xml 和/或$item 上分配了一些东西。我的代码 sn-ps 是在[xml] $xml = Get-Content ".\xmlexample.xml" 之后直接复制/粘贴
  • 我想我搞砸了。我现在可以使用您的代码-我想我从未进入过“项目”元素,这就是为什么它对我不起作用的原因。你的例子非常清晰有用,谢谢!
【解决方案2】:

Powershell xml 将 xml 文档的叶子映射为属性。此外,与 Linq-to-XML 类似,每个查询都可能返回一个元素数组。 所以你可以像这样写你的循环:

[xml]$xml = '<example>
<item>
   <productname>Hoover</productname>
</item>
<item>
   <productname>TV</productname>
</item>
<item>
  <productname>Microwave</productname>
</item>
<item>
  <productname>Computer</productname>
</item>
</example>'
$xml.example.item[1].productname = "Foo"
$xml.example.item.productname | Write-Host

结果:

Hoover
Foo
Microwave
Computer

'productname' 就像一个可以设置或检索的字符串属性。因此它没有更多的 xml 方法或属性。

【讨论】:

  • 完全准确地说,$xml.example.item.productname 是一个数组,它的每个元素都是一个字符串。
猜你喜欢
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
  • 2016-08-28
  • 2014-04-02
  • 2020-07-26
相关资源
最近更新 更多