XDocument 对不为 null 的对象的 null 引用
我有一个如下所示的 xml(称为 xdoc)文件:
<Root>
<ItemContainer>
<Item>
<Item>
<Item>
<Item>
</ItemContainer>
</Root>
如果我执行以下操作
XElement xel = xdoc.Element("ItemContainer");
据我所知,我应该返回对我的 ItemContainer 节点元素的引用,但我不断返回 null。我已经阅读了 msdn 文档
“获取具有指定的第一个(按文档顺序)子元素 X 名称。 ”
据我所知,ItemContainer 是具有指定名称的第一个子元素。我缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Do :
因为,还必须处理
。应该也有效
Do :
Because, the
<Root>
has also to be handled.should also work
我假设
xdoc
是XDocument
类型。文档的唯一子元素是根节点
。因此,您的代码应如下所示:
I assume
xdoc
is of typeXDocument
. The only child element of the document is the root node<Root>
.Because of this, your code should look like this:
你尝试过吗...
根元素是第一个元素
Have you tried ...
The root element is the first element
正如其他人所解释的,
XDocument
的唯一子元素是根元素,因此要获取根元素的子元素,您必须通过根元素:或者,您可以使用
XElement.Load()
,如果您不需要访问诸如 XML 声明之类的内容。它直接返回根元素: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:Alternatively, you can use
XElement.Load()
, if you don't need to access things like XML declaration. It returns the root element directly: