Powershell-通过XML循环
我已经循环使用了这个示例XML,我对输出每个项目的产品名称感兴趣Powershell-通过XML循环,xml,powershell,Xml,Powershell,我已经循环使用了这个示例XML,我对输出每个项目的产品名称感兴趣 <example> <item> <productname>Hoover</productname> </item> <item> <productname>TV</productname> </item> <item> <productname>Microwave</p
<example>
<item>
<productname>Hoover</productname>
</item>
<item>
<productname>TV</productname>
</item>
<item>
<productname>Microwave</productname>
</item>
<item>
<productname>Computer</productname>
</item>
</example>
如果您能提供任何帮助或建议,解释为什么这样做行不通,我们将不胜感激。它的行为就像一个没有更多子元素的子元素一样,不会以相同的方式处理。迭代
$xml.example.ChildNodes
,然后文本就是$item.productname
:
PS C:\users\IEUser\Documents> foreach ($item in $xml.example.ChildNodes) {
>>> Write-Host($item.productname)
>>> }
Hoover
TV
Microwave
Computer
或者,如果您只需要包含productname
的item
元素,则可以迭代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.example.ChildNodes
,然后文本就是$item.productname
:
PS C:\users\IEUser\Documents> foreach ($item in $xml.example.ChildNodes) {
>>> Write-Host($item.productname)
>>> }
Hoover
TV
Microwave
Computer
或者,如果您只需要包含productname
的item
元素,则可以迭代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
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
“productname”的行为类似于可以设置或检索的字符串属性。因此,它没有更多的xml方法或属性。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
“productname”的行为类似于可以设置或检索的字符串属性。因此,它没有进一步的xml方法或属性。请尝试
foreach($xml.example.ChildNodes中的项)
请尝试foreach($xml.example.ChildNodes中的项)
也许您在$xml
和/或$item
上分配了一些内容。我的代码片段是直接复制/粘贴在[xml]$xml=Get Content.“\xmlexample.xml”
之后的。我想我搞错了什么。我现在已经让你的代码工作了——我想我从来没有进入过“item”元素,这就是为什么它对我不起作用的原因。你的例子非常清楚和有用,谢谢!也许您在$xml
和/或$item
上分配了一些内容。我的代码片段是直接复制/粘贴在[xml]$xml=Get Content.“\xmlexample.xml”
之后的。我想我搞错了什么。我现在已经让你的代码工作了——我想我从来没有进入过“item”元素,这就是为什么它对我不起作用的原因。你的例子非常清楚和有用,谢谢!为了完全准确,$xml.example.item.productname
是一个数组,其每个元素都是字符串。为了完全准确,$xml.example.item.productname
是一个数组,其每个元素都是字符串。