ram
ram

Reputation: 57

How to read node values in xml by giving node id

<GlobalNavigation>
<primarylink>
<secondarylink>
    <linkid>1</linkid>
    <linkName>3</linkname>
    <secondary>
        <leftnav>
            <linkid>left1</linkid>
            <linkName>linktext</linkname>
        </leftnav>
    </secondary>
</secondarylink>
</GlobalNavigation>

i want to read leftnav linkname by giving linkid.

Upvotes: 2

Views: 592

Answers (3)

Mark Hosang
Mark Hosang

Reputation: 501

An even easier way is to use XPathing. http://msdn.microsoft.com/en-us/library/ms256086%28VS.85%29.aspx

Good thing about xpathing is that it will work in .net 2.0 AND you can get what you want in one line!...

xmlDoc.SelectSingleNode("secondaryLink/secondary/link[/linkid="123"]/linkname")

Upvotes: 1

George Polevoy
George Polevoy

Reputation: 7681

You can search it with xpath. This solution is vulnerable to injection because of string concatenation in xpath.

XElement source = ...

var linkId = "left1";

var linkName =
    source.XPathSelectElements(@"leftnav[linkid='" + linkId + @"']/linkName")
        .Select(i=>i.Value).SingleOrDefault();

I recommend to use the following:

var linkId = "left1";
var query =
 from leftNavElement in source.Descendants("leftnav")
 from linkIdElement in leftNavElement.Elements("linkid")
 where linkIdElement.Value == linkId
 from linkNameElement in leftNavElement.Elements("linkName")
 select linkNameElement.Value;

var linkName = query.SingleOrDefault();

It uses linq and handles the cases where no matching element is found.

The value of linkName will be null if there is no match in both solutions.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502446

The simplest way is to use LINQ to XML:

var doc = XDocument.Load(...);

string linkId = "left1";
var linkName = doc.Descendants("leftnav")
                  .Elements("linkid")
                  .Where(x => x.Value == linkId)
                  .Single()
                  .Parent.Element("linkName").Value;

In other words:

  • Look in each leftnav element
  • Look in each linkid element directly under it
  • Find a linkid element with the desired value
  • There should be exactly one of these (there are other options you may wish to use here, which would change the rest of the solution). Select this one linkid element.
  • Take the parent element
  • Find the first linkName element under it
  • Extract the value (i.e. the text within it)

Upvotes: 6

Related Questions