【问题标题】:Why does trying to access an attribute in LINQ-to-XML give me an error?为什么尝试访问 LINQ-to-XML 中的属性会给我一个错误?
【发布时间】:2009-08-05 15:12:52
【问题描述】:

根据我的 LINQ 书,这个稍作改动的示例应该可以工作。

为什么它告诉我“对象引用未设置为对象的实例”?

using System;
using System.Xml.Linq;

namespace TestNoAttribute
{
    class Program
    {
        static void Main(string[] args)
        {

            XDocument xdoc = new XDocument(
                new XElement("employee",
                    new XAttribute("id", "23"),
                    new XElement("firstName", new XAttribute("display", "true"), "Jim"),
                    new XElement("lastName", new XAttribute("display", "false"), "Smith")));

            XElement element = xdoc.Element("firstName");
            XAttribute attribute = element.Attribute("display"); //error

            Console.WriteLine(xdoc);

            Console.ReadLine();

        }
    }
}

部分答案:

我想如果我将 XDocument 更改为 XElement,那么它可以工作。谁能解释一下为什么

【问题讨论】:

  • 您也可以发布您的 XML 文档吗?

标签: c# linq linq-to-xml


【解决方案1】:

您正在访问不存在的 xdoc 的子元素。尝试下一级:

XElement element = xdoc.Element("employee").Element("firstName");

XElement element = xdoc.Descendants("firstName").FirstOrDefault();

【讨论】:

  • 同意,但是为什么它会在下一行代码而不是这一行抛出异常?
  • 因为在下一行代码中元素为空。如果元素不存在,则不会抛出异常(在 xdoc.Element("firstName"))。
【解决方案2】:

请参阅 MSDN 上的 this 了解原因。它明确解释了他们的“成语”,即为什么他们认为在未找到名称时返回 null 元素是有益的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 2016-08-27
    • 1970-01-01
    • 2021-08-10
    • 2013-12-07
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多