Select XML 节点基于兄弟节点的值

Select XML node based on value of sibling node

我有一个 VB.NET 2013 程序,它读取 from/writes 到一个 xml 文档,我试图弄清楚如何在知道文本的情况下访问特定节点节点的兄弟节点之一。我看过其他与我正在尝试做的事情 相似 的帖子,但我的 xml 结构略有不同,我不确定如何应用这些解决方案到我的文档。

这是我的 xml 结构的示例:

<?xml version="1.0" encoding="utf-8"?>
<Books>
  <Book>
    <Title>Hansel and Gretel</Title>
    <Pages>221</Pages>
    <Price>3.5</Price>
    <Author>Grimm</Author>
  </Book>
  <Book>
    <Title>Green Eggs and Ham</Title>
    <Pages>145</Pages>
    <Price>5.25</Price>
    <Author>Dr. Seuss</Author>
  </Book>
</Books>

我在其他帖子中看到的示例在节点名称 <Title title="Green Eggs and Ham"> 中有值。如您所见,我的没有。

我不知道如何为我的 xml 文档使用 XPath、XPathNavigator 等来查找价格,例如,如果我知道标题。

我看到很多例子看起来像:/Books/Book[@Title="Green Eggs and Ham"],我尝试将它与 XPathNavigator.SelectSingleNode() 一起使用,但我无法找出正确的 VB。 Net/XPath 语法与我的 xml 格式一起使用。

更新(示例答案) 因为我在 VB.NET 项目中使用它,所以我需要知道如何使用 Bogdan 和 ThW 提供的示例。使用我的示例 XML 我这样做是为了获得标题的页数 "Hansel and Gretel":

Dim xpathDoc As XPathDocument = New XPathDocument([path_to_xml)
Dim xmlNav as XPathNavigator = xpathDoc.CreateNavigator()
Dim pages as String

pages = xmlNav.SelectSingleNode("/Books/Book[Title='Hansel and Gretel']/Pages").Value

当然是returns“221”

//Book/Title[text()='Green Eggs and Ham']/../Price

text() 搜索值。 .. 选择父元素

编辑

感谢 ThW 关于 . 的解释,已从答案中删除。

XPath 中的 @attribute:: 的快捷方式。它选择属性节点(或属性轴上更具体的节点)。

您的Title节点是元素节点。它是 Book 元素节点的子节点。 child 是默认轴,所以它是可选的。基本上 /Books/Book/child::Books/child::Book.

的缩写

[]中的部分是节点的条件。 [@Title="Green Eggs and Ham"] 过滤具有给定值的属性 Title 的节点。

寻找子元素节点 Title 移除 @.

/Books/Book[Title="Green Eggs and Ham"]