Dexters
Dexters

Reputation: 2495

Unable to read XML correctly

I found an article to help with XML parsing: http://geekswithblogs.net/pabothu/archive/2014/04/29/reading-a-complex-xml-using-linq-in-c-sharp.aspx.

I am trying to read the XML but I am getting a null object. I am a bit confused what I am doing wrong since I am not able to debug into those LINQ queries.

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
                    })
            })
    };

And here is the 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>

Upvotes: 0

Views: 60

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

You're querying for enabled elements, but your sample XML contains enable elements. That's why you're getting NullReferenceException.

Change

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

to

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

or update your XML schema to match your query.

Upvotes: 2

Related Questions