如何根据属性值选择 XmlElement? [英] How to select an XmlElement based on an attribute value?

查看:33
本文介绍了如何根据属性值选择 XmlElement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 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 代表我通过执行从文件中读取的整个文件

I have an xmlNode representing the whole file which I read in from a file by doing

$myXml=New-Object XML
$myXml.Load("path to the books file")

然后我如何选择 id 值为bk102"的 book 元素,以便我可以将该 Xmlnode 传递给另一个需要 XMlNode 的函数?

How do I then select the book element which has the id value of "bk102" so I can then pass that Xmlnode off to another function expecting an XMlNode?

即我的新节点是:

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

谢谢大家.整个上午都在挣扎.

Thanks all. Been struggling all morning.

推荐答案

您可以使用 Where-Object 过滤书籍,或者您可以尝试 XPath.下面是两个例子:

You could filter the books using Where-Object, or you could try XPath. Here's two examples:

点导航

$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

这篇关于如何根据属性值选择 XmlElement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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