XPath 基于多个条件选择一个 XML 节点的值 [英] XPath Selecting value of an XML node based on multiple conditions
问题描述
以下 XML 表示我正在使用的更复杂结构的简化版本.我希望能够根据某些元数据选择特定值.
The following XML represents a simplified version of a more complex structure that I am working with. I want to be able to select a specific value based on some meta data.
<Root>
<Data>
<KeyValuePair>
<Key>Field1</Key>
<Value>Value1</Value>
</KeyValuePair>
<KeyValuePair>
<Key>Field2</Key>
<Value>Value2</Value>
</KeyValuePair>
<KeyValuePair>
<Key>Field3</Key>
<Value>Value3</Value>
</KeyValuePair>
</Data>
<Name>Customer</Name>
<ID>00000000-0000-0000-0000-000000000000</ID>
</Root>
我希望能够选择 Key 节点文本等于Field2"且 Name 节点等于Customer"的 Value 节点的文本.我还需要让它足够灵活,不关心命名空间.
I want to be able to select the text of the Value node where the Key node text equals "Field2" and the Name node equals "Customer". I also need to make this flexible enough to not care about namespaces.
我已经能够使用以下方法选择基于兄弟节点的节点:
I have been able to select the node based off of the sibling node using the following:
//*[local-name()='Value'][../*[local-name()='Key'][./text() = 'Field2']]/text()
但是,虽然搜索已经产生了如何根据父属性选择子节点的结果,但我一直无法找到解决我的特定困境的解决方案.
But while searching has yielded results for how to select child nodes based on parent attributes I have been unable to find a solution for my particular dilemma.
我是 XPath 的新手,所以我可能没有在寻找正确的东西,或者可能没有我想要的解决方案.无论哪种方式,如果有人能指出我正确的方向,我将不胜感激.
I am new to XPath, so I may not be searching for the correct thing or there may not be a solution for what I want. Either way, if someone could point me in the right direction it would be greatly appreciated.
为了清楚起见,我重新表述了我的问题,所提供的 XML 并不是我正在使用的,而是结构的简化表示.我还看到了关于区分大小写的评论,并编辑了我的代码以更准确地反映给定的示例.
I have rephrased my question for clarity, The XML provided is not exactly what I am working with, but a simplified representation of the structure. I have also seen comments about case sensitivity and have edited my code to more accurately reflect the given example.
推荐答案
试试这个 XPath 并记住 XPath 区分大小写:
Try this XPath and remember that XPath is case-sensitive:
//Value[../Key='Field2' and ../../../Name='Customer']/text()
这篇关于XPath 基于多个条件选择一个 XML 节点的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!