0

I'm trying to select an XML node, where another child of the parent node contains a specific value.

The XML looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<AuthorIT>
    <Objects>
        <Media>don't care</Media>
        <Style>don't care</Style>
        <Book>don't care</Book>
        <Topic>don't care</Topic>
        <Topic>
            <Object>
                <Description>Performance Evidence</Description>
            </Object>
            <Text>This is what I want to select</Text>
        </Topic>
    </Objects>
</AuthorIT>

I'm using XPath in C#. My query at the moment looks like this: (but doesn't work, obviously)

docNav = new XPathDocument(localFile);
nav = docNav.CreateNavigator();
xPath = "//Topic[Object/Description = 'Performance Evidence']/Text";
string value = nav.SelectSingleNode(xPath).Value;

How do I get the contents of the Text node, from the Topic that has an Object/Description value of "Performance Evidence"?

Adeptus
  • 138
  • 1
  • 10
  • 1
    Your XPath is correct. Can you specify what exactly is not working? – Kirill Polishchuk Sep 27 '19 at 01:07
  • @KirillPolishchuk nav.SelectSingleNode(xPath) is returning null. If I have the XPath correct, am I doing something wrong with the rest of the c#? – Adeptus Sep 27 '19 at 01:32
  • So... I've been trying to get the data through other methods. I can traverse the tree using an XmlDocument and foreach(XmlNode node in xmlNodeList), but not through xmlDocument.SelectSingleNode(...). I'd rather not have 5+ nested foreach loops just to find the node I want... Any suggestions, or should I make this a new question? – Adeptus Sep 27 '19 at 05:08
  • Made a new question. Still no solution. – Adeptus Sep 30 '19 at 02:10

2 Answers2

1

You should first select the Description node containing your needle text, then move back to the common parent and select the Text nodes that are its children.

//Topic/Object/Description[text()='Performance Evidence']/../../Text/text()
Richard Woods
  • 2,163
  • 5
  • 18
0

As Kirill Polishchuk said in a comment, my XPath was correct.

What I left out of the example XML was the key to the solution... Namespace!

I found my answer on this other question: Using Xpath With Default Namespace in C#

Adeptus
  • 138
  • 1
  • 10