2016-08-22 180 views
0

我找到了一篇幫助XML解析的文章: http://geekswithblogs.net/pabothu/archive/2014/04/29/reading-a-complex-xml-using-linq-in-c-sharp.aspx無法正確讀取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> 
+0

_「我得到一個空對象」_ - 獲取空對象在哪裏?最終的'containers'變量不能爲空。其他一些值似乎是值類型,所以也不能爲空。請更具體一些。 –

回答

2

你查詢使d元素,但示例XML包含使元素。這就是爲什麼你得到NullReferenceException

變化

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

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

或更新您的XML架構,以符合您查詢。