amigo
amigo

Reputation: 155

Parsing xml attribute value from specified node area

I have an XML which follow the following structure:

<model uir="model1">
 <profile>
  <profiles>
   <timeseries>
     <value double="24.7" index="2011-01-01 00:00" />
     <value double="24.5" index="2011-01-02 00:00" />
     <value index="2011-04-23 00:00" /> //Here for some reason i must have double=null
     <value index="2011-04-24 00:00" />
     <value double="24.7" index="2011-01-01 00:00" />
     <value double="24.5" index="2011-01-02 00:00" />

    </timeseries>
   </profile>
  </profiles>
 </model>
<model uir="model2">
 <profile>
  <profiles>
   <timeseries>
     <value double="24.7" index="2011-01-01 00:00" />
     <value double="24.5" index="2011-01-02 00:00" />
     <value index="2011-04-23 00:00" /> //Here for some reason i must have double=null
     <value index="2011-04-24 00:00" />
     <value double="24.7" index="2011-01-01 00:00" />
     <value double="24.5" index="2011-01-02 00:00" />

    </timeseries>
   </profile>
  </profiles>
 </model>

This that i want is to take the value of the attribute double and to store it in a list (or vector) for each model. When the node value hasn't an attribute double to insert a null. In first level i tried the following but when it reaches in a node with no attribute double stack.

using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

class MyClass
{
   static void Main(string[] args)
   {
        string file = @"C:\RDMS.xml";
        XDocment doc = XDocument.Load(file);
        foreach (var item in doc.Descendants("value"))
        {
            Console.WriteLine(item.Attribute("double").Value);
        }
       Console.ReadKey();
   }
} 

Upvotes: 1

Views: 146

Answers (2)

Justin Pihony
Justin Pihony

Reputation: 67075

You did not specify the error, but I am guessing you are getting a NullReferenceException? You need to check if item.Attribute actually returns a value.

var doubleAttr = item.Attribute("double");
if(doubleAttr == null) continue;
Console.WriteLine(item.Attribute("double").Value);

If that is not your problem, then please be more specific as to what your problem is.

Further clarification from trope's comment below:

...you are getting a NullReferenceException because nothing returns from item.Attribute("double") for the elements that lack that attribute, therefore you cannot then call .Value, as item.Attribute("double") is null, and you receive a NullReferenceException. This does not happen with your index attribute, because all of your "value" elements have index attributes...

Upvotes: 1

Koopakiller
Koopakiller

Reputation: 2884

You can check the result of Attribute(string) if it is null:

var attrib = item.Attribute("double");
if (attrib != null)
    Console.WriteLine(attrib.Value);
else
    Console.WriteLine("attribute not found!");

Upvotes: 0

Related Questions