简体   繁体   中英

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? Basically I want to search for only sibling value elements in which one of its sibling ./value/string text contains ErrorCode ?

You should use this XPath expression:

/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

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.

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

C# version:

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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