2017-05-04 62 views
0

我有這個代碼,我試圖運行。有沒有辦法驗證我收到的內容是href並將它寫在屏幕上?我的foreach循環有什麼問題嗎?

[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> 
+0

這不是我清楚你想要達到的目標。你是什​​麼意思「驗證內容是'href'」?你想驗證(''?)節點包含'href'屬性嗎?該網址是有效的?您希望從您的樣本輸入中得到什麼樣的輸出? –

回答

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 
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 
+0

是不是正則表達矯枉過正以獲得'href's? – SomeDude

+0

@svasa取決於他的需求。這是更少的代碼,不需要XML解析。所以可能不會。 –