【问题标题】:xPath to get sibling value for element with specific valuexPath 获取具有特定值的元素的兄弟值
【发布时间】:2013-02-20 21:02:51
【问题描述】:

鉴于此 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>

我需要根据特定的游戏 ID 获取抽奖号码。例如,如果我指定 gameID L649,我需要得到 3035。

以下内容适用于多个在线评估器,但不适用于 C#。它说它找不到它。有什么建议吗?

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

我尝试过的 C# 代码:

XmlNode node = xmlDoc.SelectSingleNode("/InitResponse/GameInfoList/GameInfo/Draw/draw[preceding-sibling::gameId='L649']");

... 其中 xmlDoc 是与 xml 一起加载的 xmlDocument 对象。节点变量以空值结束,这似乎表明没有找到匹配项。

【问题讨论】:

  • 你应该使用XPath

标签: c# xml xpath


【解决方案1】:

这里是 xpath(带有 Linq)

var xdoc = XDocument.Load(path_to_xml);
string xpath = "/InitResponse/GameInfoList/GameInfo/Draw[gameId='L649']/draw";
var draw = xdoc.XPathSelectElement(xpath);
if (draw != null) // check if draw with gameId found in xml
    value = (int)draw;

您也可以使用纯 Linq to Xml(但在这种情况下,xpath 看起来更紧凑):

var draw = xdoc.Descendants("GameInfo")
               .SelectMany(g => g.Elements("Draw"))
               .SingleOrDefault(d => (string)d.Element("gameId") == "L649");
if (draw != null)
    value = (int)draw.Element("draw");

【讨论】:

    【解决方案2】:

    使用 XmlDocument

    我在您的XPath 声明中没有发现任何问题,请查看以下内容:

    (所以我猜还有其他问题)

    XmlDocument myDoc = new XmlDocument();
    
    String str = @"<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>";
    
                myDoc.LoadXml(str);
    
                XmlNode node =
                    myDoc.SelectSingleNode("/InitResponse/GameInfoList/GameInfo/Draw/draw[preceding-sibling::gameId='L649']");
    

    结果返回的节点是:3035

    注意:您的第一个注释必须是 &lt;InitResponse&gt; 否则它将返回 null

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 2022-08-23
      相关资源
      最近更新 更多