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"?

4
  • 1
    Your XPath is correct. Can you specify what exactly is not working? Commented Sep 27, 2019 at 1: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#? Commented Sep 27, 2019 at 1: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? Commented Sep 27, 2019 at 5:08
  • Made a new question. Still no solution. Commented Sep 30, 2019 at 2:10

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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#

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.