【问题标题】:Is there anything wrong with my foreach loop?我的 foreach 循环有什么问题吗?
【发布时间】:2017-10-02 15:35:34
【问题描述】:

我有这段代码,我正在尝试运行。有没有办法验证我得到的内容是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>

【问题讨论】:

  • 我不清楚你想要实现什么。 “验证内容是href”是什么意思?是否要验证 (&lt;name&gt;?) 节点是否包含 href 属性?该 URL 是否有效?您期望样本输入的输出是什么?

标签: xml powershell foreach


【解决方案1】:

您可以执行以下操作:

[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

【讨论】:

    【解决方案2】:

    如果您只想打印 href 标记内的所有链接,您也可以使用 regex 获取那些链接:

    $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
    

    【讨论】:

    • 获取hrefs 的正则表达式不是矫枉过正吗?
    • @svasa 取决于他的需要。它的代码更少,不需要 xml 解析。所以可能不会。
    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多