开发者

XDocument null reference on object that isnt null

开发者 https://www.devze.com 2023-04-07 20:22 出处:网络
I have an xml (called xdoc) file like the following: <Root> <ItemContainer> <Item> <Item>

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?


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


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");


Have you tried ...

xdoc.Root.Element("ItemContainer");

The root element is the first element


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消