【问题标题】:How do I access an element with xpath with a namespace in powershell?如何在 powershell 中使用带有命名空间的 xpath 访问元素?
【发布时间】:2013-10-18 23:51:53
【问题描述】:

Powershell:

$doc = new-object System.Xml.XmlDocument
$doc.Load($filename)

$items = Select-Xml -Xml $doc -XPath '//item'
$items | foreach {
    $item = $_
    write-host $item.name
}

我没有输出

XML:

<?xml version="1.0" encoding="UTF-8"?>
<submission version="2.0" type="TREE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="TREE.xsd" xmlns="some/kind/of/tree/v1">
  <group>
    <item></item>
    <item></item>
    <item></item>
  </group>
<submission>

【问题讨论】:

    标签: xml powershell xpath xml-namespaces


    【解决方案1】:

    您遇到了一些问题。首先,您需要在 XPath 模式中指定命名空间,XML 格式不正确(结束标记不是结束标记)并且 Select-Xml 返回 XmlInfo 而不是直接返回 XmlElement。试试这个:

    $xml = [xml]@'
    <submission version="2.0" type="TREE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="TREE.xsd" xmlns="some/kind/of/tree/v1">
      <group>
        <item></item>
        <item></item>
        <item></item>
      </group>
    </submission>
    '@
    
    $ns = @{dns="some/kind/of/tree/v1"}
    $items = Select-Xml -Xml $xml -XPath '//dns:item' -Namespace $ns
    $items | Foreach {$_.Node.Name}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-28
      • 2012-10-03
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多