Linq > Get XML Node

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
 
M

Marc Gravell

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
 
J

Jeroen Mostert

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

XML ID ... 7
XML to Dictionary using LINQ 2
Delete record. Fire exception 2
How to get an XNode using Linq to XML? 6
XML Document. How can I do this? 1
Byte Array 4
Create XML File 1
Delete and Update 2

Top