tags:

views:

72

answers:

3

My xml looks like this:

<nodes><skus><sku>abc</sku><sku>def123</sku></skus></nodes>

I want to get all the elements with the name 'sku'

I have a XDocument already loaded with the xml.

List<XElement> elements = doc.Elements.Where( ??? )

or would I just do:

doc.Elements("sku")

?

I don't want this to return an error if there are no elements.

A: 

You want a nodelist of the elements of that tag name:

XmlNodeList nodes = doc.GetElementsByTagName("sku");
SnOrfus
The OP is using Linq to XML, not XML DOM ;)
Thomas Levesque
ah. Didn't notice. Thought that xdocument was a typo of xmldocument.
SnOrfus
+3  A: 

Elements() only returns the direct children of a node.

doc.Descendants("sku");

should do the trick. It searches along the descendants axis.

Obalix
shouldn't it be skus and not sku?
Blankman
In your OP you wanted all sku in the document (`doc.Elements("sku")`) so that's what I did. If you want the skus you can do `doc.Descendants("skus")` it depends what you want.
Obalix
+1  A: 

Hi there.

static void Main(string[] args)
        {
            var g = XDocument.Parse("<nodes><skus><sku>abc</sku><sku>def123</sku></skus></nodes>");

            var t = from e in g.Descendants("sku")
                    select e;

        }

EDIT: I started this example, but got interrupted - I'm determined to get this code on SO even if it kills me!!

Cheers. Jas.

Jason Evans
this will return a nodelist then?
Blankman
*from e in g.Descendants("sku") select e* : this is the same as *g.Descendants("sku")*, it just adds one more iterator level...
Thomas Levesque
@Blankman: `g.Descendants("sku")` returns `IEnumerable<XElement>`.
Obalix