0
<node label="Chemist Name">
    <node label="John,Smith" searchId="1122" />
</node>

Hi,

if i have the above as part of my xml structure, and i want to find a tag where the parent has a label of "Chemist Name" and its inner tag has a label of John,Smith so i can then get the searchid - what would be the best way of doing it?

is there a way where i can, rather than unefficiently looping through every xml value in my document just directly say

"get me the node where its parent is chemist name and its child has a label of john smith"

thanks

2 Answers 2

3

Use XPath with the following query:

//node[@label = "Chemist Name"]/node[@label = "John,Smith"]

You can use it like this in C#:

var doc = new XmlDocument();
doc.LoadXml(xml);
var node = doc.SelectSingleNode(
        @"//node[@label = ""Chemist Name""]/node[@label = ""John,Smith""]");

Where xml is a string containing the XML data. If you want to load the XML directly from disc, use XmlDocument.Load() instead.

Sign up to request clarification or add additional context in comments.

5 Comments

where node is the xml document?
great thanks for that - i guess this is a handy tool i need to learn. would you say its more efficinet or does this kind of approach have an overhead too?
@ricki: If your XML document is huge, this is not the best way to do it, because XmlDocument first reads the whole file and then applies the XPath query. If you have a huge XML document, a SAX parser like XmlReader would be more suitable. But in general, XPath is the way to go, if you want to find a node, that's what it was invented for.
@Daniel Hilgarth - i have replaced the names with parameters and i get an invalid token exception, i cant really see what i have done wrong - "'//node[@label = Chemist Name]/node[@label = John,Smith]' has an invalid token."
@ricki: The attribute values (Chemist Name and John, Smith) need to be in quotes.
0

xpath is the way to go with this. you should read more on the XPathNavigator, and xpath. If you're stuck, post back and we can help out.

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.