LINQ to XML question

M

Matthias S.

hello,

i've got the following xml structure:

<catalog>
<books>
<item key="" value="" />
<item key="" value="" />
...
</books>
<cds>
<item key="" value="" />
<item key="" value="" />
...
</cds>
</catalog>

now i'd like to build a query which will select all <item> elements in
a given section (e.g. books). i don't manage to get this straight. as
well i can't figure out how to retrieve the count on a anonymous
type/collection returned from a linq query. my linq book is ordered and
on its way, but not here yet. :)

could anyone please shed some light? thanks in advance.

matthias
--
 
M

Martin Honnen

Matthias said:
i've got the following xml structure:

<catalog>
<books>
<item key="" value="" />
<item key="" value="" />
...
</books>
<cds>
<item key="" value="" />
<item key="" value="" />
...
</cds>
</catalog>

now i'd like to build a query which will select all <item> elements in
a given section (e.g. books).

XDocument doc = XDocument.Load(@"catalog.xml");
IEnumerable<XElement> bookItems =
doc.Root.Element("books").Elements("item");
IEnumerable<XElement> cdItems =
doc.Root.Element("cds").Elements("item");

That simply selects the 'item' XElement objects. If you want to populate
some anonymous type then do it like this:

XDocument doc = XDocument.Load(@"..\..\XMLFile1.xml");

var query =
from item in doc.Root.Element("books").Elements("item")
select new { key = (string)item.Attribute("key"), value
= (string)item.Attribute("value") };

foreach (var item in query)
{
Console.WriteLine("{0}: {1}.", item.key, item.value);
}
 
M

Matthias S.

that helped. thank you a ton.
--



Martin said:
XDocument doc = XDocument.Load(@"catalog.xml");
IEnumerable<XElement> bookItems =
doc.Root.Element("books").Elements("item");
IEnumerable<XElement> cdItems =
doc.Root.Element("cds").Elements("item");

That simply selects the 'item' XElement objects. If you want to
populate some anonymous type then do it like this:

XDocument doc = XDocument.Load(@"..\..\XMLFile1.xml");

var query =
from item in
doc.Root.Element("books").Elements("item") select new
{ key = (string)item.Attribute("key"), value =
(string)item.Attribute("value") };

foreach (var item in query)
{
Console.WriteLine("{0}: {1}.", item.key, item.value);
}
 

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

Top