我的foreach循环有什么问题吗?

时间:2017-05-04 12:39:17

标签: xml powershell foreach

我正在尝试运行此代码。有没有办法验证我得到的内容是href并将其写在屏幕上?

[System.Xml.XmlDocument] $xd = New-Object System.Xml.XmlDocument
$file = Resolve-Path("D:\Powershell\XML\iptree.xml")
$xd.Load($file)
$nodelist = $xd.SelectNodes("/name/@*") # XPath is case sensitive
foreach ($attr in $nodelist) {
  Write-Host "xml data " $attr
}

XML文件

<?xml version="1.0"?>
<root>
<item id="Integrated Projects - XYZ">
<content><name><![CDATA[Integrated Projects - XYZ]]></name></content>
<item id="67e26e0e-32ad-432b-b054-7666301539ca">
<content><name href="https://inside.nov.com/ipeh/107377" target="_blank" ><![CDATA[377 - Train - ]]></name></content>
</item>
<item id="e9e91ec2-59c0-4122-b4f9-feb2aff6b2a6">
<content><name href="https://inside.nov.com/ipeh/107378" target="_blank" ><![CDATA[78 - Energy]]></name></content>
</item>
<item id="34043397-ec4b-480c-99c4-110f79e505bb">
<content><name href="https://inside.nov.com/ipeh/120025" target="_blank" ><![CDATA[25-Gam]]></name></content>
</item>
<item id="afe44549-b1ab-420c-b43a-fdd0ddbf7a7c">
<content><name href="https://inside.nov.com/ipeh/120026" target="_blank" ><![CDATA[26 - Pevamping]]></name></content>
</item>
</item>
</root>

2 个答案:

答案 0 :(得分:0)

如果您只想打印 href 标记内的所有链接,您还可以使用正则表达式来抓取这些链接:

$content = Get-Content 'D:\Powershell\XML\iptree.xml' -raw
[regex]::Matches($content, 'href="([^"]+)') | ForEach-Object{ 
    $_.Groups[1].Value
}

<强>输出:

https://inside.nov.com/ipeh/107377
https://inside.nov.com/ipeh/107378
https://inside.nov.com/ipeh/120025
https://inside.nov.com/ipeh/120026

答案 1 :(得分:0)

您可以执行以下操作:

[System.Xml.XmlDocument] $xd = new-object System.Xml.XmlDocument
$file = resolve-path("D:\Powershell\XML\iptree.xml")
$xd.load($file)
$nodelist = $xd.selectnodes("//name/@href") # XPath is case sensitive
foreach ($attr in $nodelist) 
{
  write-host "xml data " $attr.value

}

为了获得href属性,xpath应为//name/@href并使用$attr.value写入主机。

xml的输出:

xml data  https://inside.nov.com/ipeh/107377
xml data  https://inside.nov.com/ipeh/107378
xml data  https://inside.nov.com/ipeh/120025
xml data  https://inside.nov.com/ipeh/120026