遍历XML

时间:2018-12-16 13:06:39

标签: powershell

我有一些代码似乎可以正常工作,因为它可以打印我期望的代码,但似乎至少有一对多的foreach语句。最初我确实在JSON中具有相同的数据,但是为了使其与PS2一起使用,我认为XML将使此操作变得更容易。相比之下,JSON版本似乎相当简单。代码如下所示。如果这是正确的,我将不胜感激。我相信必须有更好的方法。

$xmldata = [xml]@"
<?xml version="1.0" encoding="UTF-8"?>
<DATA>
   <Components>
         <ITEM1>
         <name>
        <element>test1</element>
     </name>
     <info1>
        <element>info1-e1</element>
        <element>info1-e2</element>
     </info1>
     <info2>
        <element>info2-e1</element>
        <element>info2-e2</element>
     </info2>
    </ITEM1>
     <ITEM2>
     <name>
        <element>test2</element>
     </name>
     <info2>
        <element>info2-e1</element>
        <element>info2-e2</element>
     </info2>
     <info2>
        <element>info2-e1</element>
        <element>info2-e2</element>
     </info2>
     </ITEM2>
  </Components>
</DATA>
"@

$xmldata | Select-Xml -XPath "//DATA/Components" | foreach {
    foreach ($x in $_.node) {
        foreach ($itemToProcess in $x.ChildNodes) {
            Write-Host "Name:" $($itemToProcess.name.element)

            #Process Info1
            if ($itemToProcess.info1) {
                foreach ($e in $itemToProcess.info1.element) {
                    Write-Host "`tElement:" $e
                }
            }

            #Process Info2
            if ($itemToProcess.info2) {
                foreach ($e in $itemToProcess.info2.element) {
                    Write-Host "`tElement:" $e
                }
            }
        }
    }
}

这是答案吗?还是我还没有想办法?我的foreach少了一个。

$l1 = 0 
$l2 = 0

$xmldata | Select-Xml -XPath "//DATA/Components" | foreach {
    foreach ($itemToProcess in $_.node.ChildNodes) {
        Write-Host "Name:" $($itemToProcess.name.element)

        #Process Info1
        if ($itemToProcess.info1) {
            foreach ($e in $itemToProcess.info1.element) {
                Write-Host "`tElement:" $e
            }
        }

        #Process Info2
        if ($itemToProcess.info2) {
            foreach ($e in $itemToProcess.info2.element) {
                Write-Host "`tElement:" $e             
            }
        }
        $l2++
    }
    $l1++
}

Write-Host "Number of outer foreach" $l1
Write-Host "Number of inner foreach" $l2

0 个答案:

没有答案