遍历 xml 标签的每个实例

iterating through every instance of xml tag

我是 Powershell 的新手,我正在尝试阅读 XML 文档,然后对于每个名为 <document> 的节点,我想查看其中的内容。

不太确定如何在 powershell 中执行此操作。目前,我只查看名为 <document> 的第一个实例,然后查看其中的内容。但是一个文件可以有多个名为 <document> 的节点,例如示例中的

如何获取每个名为 document 的节点的实例,然后 foreach 通过它们?理想情况下,我希望返回一个名为 document 的节点列表,然后我可以遍历它们。

<List state='null'>
    <document>
        <i_state>null</i_state>
        <i_toronto>qwe</i_toronto>
        <i_site>123</i_site>
        <i_library>potluck</i_library>
        <i_url>www.google.com</i_url>
        <mmdete>
            <metafy>Oblong</metafy>
        </mmdete>
       </document>
    <document>
        <i_state>null</i_state>
        <i_toronto>qwe</i_toronto>
        <i_site>123</i_site>
        <i_lib>potluck</i_lib>
        <i_url>https:www.google.com</i_url>
        <mmdete>
            <metafy>Oblong</metafy>
        </mmdete>
       </document>

</List>

你可以用 SelectNodes('//nodename'):

$XmlFile = [xml](Get-Content .\file.xml)
$XmlFile.SelectNodes('//document') |ForEach-Object {
    $_ # this now refers to a "document" XmlNode
}

PowerShell 与 XML 一起工作得很好,只要它知道它正在寻找什么。如果将变量设为 [XML] 类型,则可以通过多种方法相当轻松地引用这些文档节点。例如,我将您的示例保存为 'testdata.txt' 并执行了以下操作:

[xml]$source = get-content testdata.txt
$source.list.document

PowerShell 返回以下内容:

i_state   : null
i_toronto : qwe
i_site    : 123
i_library : potluck
i_url     : www.google.com
mmdete    : mmdete

i_state   : null
i_toronto : qwe
i_site    : 123
i_lib     : potluck
i_url     : https:www.google.com
mmdete    : mmdete

如果您不知道节点的位置,您可以使用 Select-XML cmdlet 通过 xpath 搜索您的节点。

$source|select-xml -XPath '//document'|select -expand node

这将提供相同的输出。