如何根据属性值选择XmlElement?

时间:2015-01-08 13:40:05

标签: xml powershell

说我有以下xml

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>      
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>     
   </book>
</catalog>

我有一个xmlNode,表示我通过

从文件读入的整个文件
$myXml=New-Object XML
$myXml.Load("path to the books file")

然后如何选择id值为&#34; bk102&#34;的书元素。那么我可以将Xmlnode传递给另一个期待XMlNode的函数吗?

,即我的新节点将是:

$Node = <book id="bk102">
       <author>Ralls, Kim</author>
    </book>

谢谢大家。整个上午都在苦苦挣扎。

1 个答案:

答案 0 :(得分:1)

您可以使用Where-Object过滤图书,也可以尝试使用XPath。这是两个例子:

<强>斑点导航

$bookid = 'bk102'
$myxml = [xml](Get-Content '.\New Text Document.txt')

$node = $myxml.catalog.book | Where-Object { $_.id -eq $bookid }
$node

id                                                         author
--                                                         ------
bk102                                                      Ralls, Kim

<强>的XPath

$bookid = 'bk102'
$myxml = [xml](Get-Content '.\New Text Document.txt')

$node = $myxml.SelectSingleNode("catalog/book[@id='$bookid']")
$node

id                                                         author
--                                                         ------
bk102                                                      Ralls, Kim