如何在powershell中使用带有命名空间的xpath访问元素? [英] How do I access an element with xpath with a namespace in powershell?

查看:45
本文介绍了如何在powershell中使用带有命名空间的xpath访问元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Powershell:

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>

推荐答案

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

You've got a few problems going on. First you need to specify the namespace in the XPath pattern, the XML isn't well formed (closing tag is not an end tag) and Select-Xml returns XmlInfo and not XmlElement directly. Try this:

$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}

这篇关于如何在powershell中使用带有命名空间的xpath访问元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆