2

I want to select a node where inner text of cat is 'PG' using XPath

<?xml version="1.0" encoding="utf-8"?>
<Students>
    <student>
        <name>Talha</name>
        <cat>PG</cat>
    </student>
    <student>
        <name>irfan</name>
        <cat>UG</cat>
    </student>
    <student>
        <name>Ali</name>
        <cat>PG</cat>
    </student>
    <student>
        <name>Umer</name>
        <cat>UG</cat>
    </student>
</Students>

Code which I tried is this

XmlElement xmldoc = (XmlElement)doc.DocumentElement
    .SelectSingleNode("/Students/student/*[*[local-name()='cat']='PG']");
1
  • 1
    What's with the local-name() call? That's suspicious. You don't need that unless your actual XML has namespaces, and even then you don't really need it. So... does your actual XML have namespaces? If yes, show your actual XML. If not, get rid of local-name(). Commented Dec 21, 2017 at 20:15

1 Answer 1

1

To select all the student nodes which sub-elements cat have the value 'PG' use this XPath expression

/Students/student[cat='PG']

To only get the first one use

/Students/student[cat='PG'][1]

So in the syntax of C# use

XmlElement xmldoc = (XmlElement)doc.DocumentElement.SelectSingleNode("/Students/student[cat='PG'][1]");
Sign up to request clarification or add additional context in comments.

2 Comments

SelectSingleNode will only select a single node. No need for [1], right?
@ThomasWeller: Yes. I only added that to emphasize that it's the first node of the two to be selected.

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.