1

I have an xml (called xdoc) file like the following:

<Root>
<ItemContainer>
<Item>
<Item>
<Item>
<Item>
</ItemContainer>
</Root>

if i do the following

XElement xel = xdoc.Element("ItemContainer");

As far as i understand, i should get back a reference to to my ItemContainer node element, but i keep getting back null. Ive read the msdn docs for this

"Gets the first (in document order) child element with the specified XName. "

as far as i can see, ItemContainer is the first child element with the specified name. What am i missing?

richzilla
  • 40,440
  • 14
  • 56
  • 86
  • Is `xdoc` not maybe `null`? Make sure `xdoc` was loaded... How do you populate `xdoc`? – Willem Sep 26 '11 at 08:49
  • `XDocument xdoc = XDocument.Load(@"c:\projects\gen\test_xml.xml");` Ive put a breakpoint on xdoc and everything has loaded as expected – richzilla Sep 26 '11 at 08:50

4 Answers4

4

Do :

XElement xel = xdoc.Root.Element("ItemContainer");

Because, the <Root> has also to be handled.

XElement xel = xdoc.Element("Root").Element("ItemContainer");

should also work

Steve B
  • 36,818
  • 21
  • 101
  • 174
1

I assume xdoc is of type XDocument. The only child element of the document is the root node <Root>.
Because of this, your code should look like this:

XElement xel = xdoc.Root.Element("ItemContainer");
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

Have you tried ...

xdoc.Root.Element("ItemContainer");

The root element is the first element

ColinE
  • 68,894
  • 15
  • 164
  • 232
1

As others explained, the only child of an XDocument is the root element, so to get to a child of the root, you have to get through the root:

XElement xel = xdoc.Root.Element("ItemContainer");

Alternatively, you can use XElement.Load(), if you don't need to access things like XML declaration. It returns the root element directly:

XElement root = XElement.Load(@"c:\projects\gen\test_xml.xml");
XElement xel = root.Element("ItemContainer");
svick
  • 236,525
  • 50
  • 385
  • 514