471,348 Members | 1,324 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,348 software developers and data experts.

Linq > Get XML Node

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
Sep 7 '08 #1
2 7173
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
Sep 7 '08 #2
shapper wrote:
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 <galleryelement, 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.

--
J.
Sep 7 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Christian Schmidbauer | last post: by
28 posts views Thread by Marc Gravell | last post: by
reply views Thread by Guzeppi | last post: by
6 posts views Thread by hon123456 | last post: by
reply views Thread by Iaml | last post: by
1 post views Thread by Amil Hanish | last post: by
2 posts views Thread by shapper | last post: by
1 post views Thread by Ronak mishra | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.