开发者

C# XPATH Select Attribute where child node inner Text is

I have this XML File:

<?xml version="1.0" encoding="UTF-8"?>
<karteikasten>
  <vokabel stufe="1">
    <eng>
      <item>Hi</item>
      <item>Hello</item>
    </eng>
    <de>
      <item>Hallo</item>
      <item>Moin</item>
    </de>
  </vokabel>
  <vokabel stufe="1">
    <eng>
      <item>Eating</item>
    </eng>
    <de>
      <item>Essen</item>
      <item>Mampfen</item>
    </de>
  </vokabel>
</karteikasten>

I want to select the Attribute "stufe" where <item> is "Hi", "Hello" or whatever. I have this code, which works:

XPathDocument document = new XPathDocument(@"C:\test.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathExpression expression;
expression = navigator.Compile("/karteikasten/vokabel[eng/item]/@stufe");
XPathNodeIterator iterator = navigator.Select(expression);

while (iterator.MoveNext())
{
  XPathNavigator navigator2 = iterator.Current.Clone();
  Console.WriteLine(na开发者_开发技巧vigator2.Value);
}

But this selects every "stufe" in the whole document.

expression = navigator.Compile("/karteikasten/vokabel[eng/item='Hi']/@stufe");

Doesn't work. What's the right pattern to get what I want?


In some parsers, your expression will actually work as written. In .NET, I believe you need to use the text() function, as in:

/karteikasten/vokabel[eng/item/text()='Hi']/@stufe


Try:

expression = navigator.Compile("/karteikasten/vokabel[eng/item='Hi' and @stufe='1']/@stufe");

that should work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜