C# 无法正确读取XML

C# 无法正确读取XML,c#,xml,linq,C#,Xml,Linq,我发现了一篇有助于XML解析的文章: 我试图读取XML,但得到了一个空对象。我有点困惑我做错了什么,因为我无法调试到那些LINQ查询中 var containers = from container in xmlDoc.Descendants("container") //where container.Attribute("ID").Value != "0" select new Container { id = Convert.ToInt32

我发现了一篇有助于XML解析的文章:

我试图读取XML,但得到了一个空对象。我有点困惑我做错了什么,因为我无法调试到那些LINQ查询中

var containers =
    from container in xmlDoc.Descendants("container")
    //where container.Attribute("ID").Value != "0"
    select new Container
    {
        id = Convert.ToInt32(container.Element("id").Value),
        name = container.Element("name").Value,
        enabled = Convert.ToBoolean(container.Element("enabled").Value),
        components = new List<Component>(
            from component in container.Descendants("component")
            select new Component
            {
                id = Convert.ToInt32(component.Element("id").Value),
                name = component.Element("name").Value,
                type = component.Element("type").Value,
                connectors = new List<Connector>(
                    from connector in component.Descendants("connector")
                    select new Connector
                    {
                        id = Convert.ToInt32(component.Element("id").Value),
                        name = connector.Element("name").Value,
                        source = connector.Element("id").Value,
                        destination = component.Element("id").Value
                    })
            })
    };
下面是XML:

<?xml version="1.0" encoding="UTF-8"?>
<simplevisio>
  <container>
    <id>1</id>
    <name>Naming</name>
    <component>
      <id>2</id>
      <type>Server</type>
      <name>First</name>
      <connector>
        <id>3</id>
        <name>.</name>
      </connector>
      <connector>
        <id>5</id>
        <name>isShortName()</name>
      </connector>
    </component>
    <component>
      <id>3</id>
      <type>Server</type>
      <name>Last</name>
      <connector>
        <id>5</id>
        <name>isShortName()</name>
      </connector>
    </component>
    <enable>true</enable>
    <connector>
      <id>5</id>
      <name>getFullname()</name>
    </connector>
  </container>
  <container>
    <id>4</id>
    <name></name>
    <component>
      <id>5</id>
      <type>Server</type>
      <name>FirstLast</name>
    </component>
    <enable>false</enable>
  </container>
</simplevisio>
您正在查询启用的元素,但示例XML包含启用元素。这就是为什么会出现NullReferenceException

改变

enabled = Convert.ToBoolean(container.Element("enabled").Value),

或者更新XML架构以匹配查询。

您正在查询启用的元素,但示例XML包含启用元素。这就是为什么会出现NullReferenceException

改变

enabled = Convert.ToBoolean(container.Element("enabled").Value),

或者更新XML模式以匹配查询。

我得到一个空对象-在哪里得到空对象?最后一个containers变量不应为null。其他一些值似乎是值类型,因此也不能为null。请更具体一点。我得到一个空对象-得到一个空对象在哪里?最后一个containers变量不应为null。其他一些值似乎是值类型,因此也不能为null。请说得更具体些。