XDocument 对不为 null 的对象的 null 引用

发布于 2024-12-06 15:13:53 字数 461 浏览 0 评论 0原文

我有一个如下所示的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

又爬满兰若 2024-12-13 15:13:53

Do :

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

因为,还必须处理

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

应该也有效

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

仅此而已 2024-12-13 15:13:53

我假设 xdocXDocument 类型。文档的唯一子元素是根节点
因此,您的代码应如下所示:

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

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");
我只土不豪 2024-12-13 15:13:53

你尝试过吗...

xdoc.Root.Element("ItemContainer");

根元素是第一个元素

Have you tried ...

xdoc.Root.Element("ItemContainer");

The root element is the first element

如梦亦如幻 2024-12-13 15:13:53

正如其他人所解释的, XDocument 的唯一子元素是根元素,因此要获取根元素的子元素,您必须通过根元素:

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

或者,您可以使用 XElement.Load(),如果您不需要访问诸如 XML 声明之类的内容。它直接返回根元素:

XElement root = XElement.Load(@"c:\projects\gen\test_xml.xml");
XElement xel = root.Element("ItemContainer");

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");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文