Linq > Get XML Node

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I am trying to get the node "album" in a XML file given its "id"
attribute:

<gallery>
<album
id = "1"
title="Intro"
....

So in this case I would like to get the album with id = "1" under
gallery. I am using the following:ml"));

XDocument file = XDocument.Load(path);

XElement node =
file.Document.Element("gallery").Elements("album")

I just don't know how to select the album node with ID = "1".

How to do this?

Thanks,
Miguel
 
Well, I don't know XDocument very well, but it would be trivial in
XmlDocument:

XmlElement el = (XmlElement)file.SelectSingleNode("/gallery/
album[@id='1']");

Marc
 
shapper said:
I am trying to get the node "album" in a XML file given its "id"
attribute:

<gallery>
<album
id = "1"
title="Intro"
...

So in this case I would like to get the album with id = "1" under
gallery. I am using the following:ml"));

XDocument file = XDocument.Load(path);
Using XElement directly is usually simpler. XDocument is almost never required.
XElement node =
file.Document.Element("gallery").Elements("album")
file.Document is redundant; you can access the elements of the document
directly.
I just don't know how to select the album node with ID = "1".
Let's say "gallery" holds the <gallery> element, then

XElement album = (
from a in gallery.Elements("album")
where (int) a.Attribute("id") == 1
select a
).First();

should do it. This assumes that every album has an id and that there is an
album with id 1. A more robust version is

XElement album = (
from a in gallery.Elements("album")
where (int?) a.Attribute("id") == 1
select a
).FirstOrDefault();

This will return null if no such album exists, and it won't fail if there
are albums without ids.

You can rewrite these as simple expressions if you're so inclined:

XElement album = gallery.Elements("album").FirstOrDefault(a => (int?)
a.Attribute("id") == 1);

Some people prefer the query syntax even for simple queries.
 
Back
Top