简体   繁体   English

如何根据同级xml节点中同级节点中的文本值查找文本?

[英]How do I find the text of a sibling xml node based on the text value in its sibling node?

Given: 鉴于:

<param>
<data>
    <value><string>ErrorCode</string></value>
    <value><string>200</string></value>
</data>
<data>
    <value><string>Desc</string></value>
    <value><string>Age group</string></value>
</data>
</param>

How can I construct an xpath to return me the node /param/data/value/string where its text value is 200? 我该如何构造一个xpath来返回文本值为200的节点/param/data/value/string Basically I want to search for only sibling value elements in which one of its sibling ./value/string text contains ErrorCode ? 基本上我只想搜索同级./value/string文本之一包含ErrorCode同级value元素?

You should use this XPath expression: 您应该使用以下XPath表达式:

/param/data/value/string[../preceding-sibling::value[string='ErrorCode']|../following-sibling::value[string='ErrorCode']]

If the order of your values is always the same, you can remove the union operator and use only one part of the predicate. 如果值的顺序始终相同,则可以删除并运算符并仅使用谓词的一部分。

For those interested I had a very similar need and had to do it slightly differently. 对于那些感兴趣的人,我有非常相似的需求,并且必须做些微的不同。

I needed to get the value if a sibling within the same node based on another sibling. 如果同一节点内的兄弟姐妹基于另一个兄弟姐妹,则需要获取值。 So, in the following example I needed to get the draw number based on a specific gameId 因此,在下面的示例中,我需要根据特定的gameId获取抽奖编号

XML: XML:

<InitResponse>
  <LottoToken>908ec70b308adf10d04db1478ef9b01b</LottoToken>
  <GameInfoList>
    <GameInfo>
      <Draw>
        <gameId>L649</gameId>
        <draw>3035</draw>
      </Draw>
    </GameInfo>
    <GameInfo>
      <Draw>
        <gameId>BC49</gameId>
        <draw>2199</draw>
      </Draw>
    </GameInfo>
  </GameInfoList>
</InitResponse>

I needed to use the following syntax. 我需要使用以下语法。 It works in several on-line xPath evaluators but I had trouble with it in C# and had to use a different approach. 它可以在多个在线xPath评估器中使用,但是我在C#中遇到了麻烦,不得不使用其他方法。

/InitResponse/GameInfoList/GameInfo/Draw/draw[preceding-sibling::gameId='L649']

C# version: C#版本:

string s = @"
<param>
<data>
    <value><string>ErrorCode</string></value>
    <value><string>200</string></value>
</data>
<data>
    <value><string>Desc</string></value>
    <value><string>Age group</string></value>
</data>
</param>";

XDocument xdoc = XDocument.Parse(s);

foreach (var elem in xdoc.XPathSelectElements("/param/data/value[string='ErrorCode']"))
{
    XName value = XName.Get("value");
    foreach (var res in elem.ElementsBeforeSelf(value).Union(elem.ElementsAfterSelf(value)).Select(el => el.XPathSelectElement("string").Value))
        Console.WriteLine(res);
}

尝试以下Xpath

//param/data/value[string='ErrorCode']/following-sibling::value/string | //param/data/value[string='ErrorCode']/preceding-sibling::value/string 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM