0

I am trying to read an xml file and get attribute but sometime this attribute doesn't exist.

When it doesn't exist, I get this error :

System.Linq.Enumerable+WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,<>f__AnonymousType02[System.String,System.String]]

And :

Critical Error : System.NullReferenceException:....

My code :

string url = @"http://vigilance.meteofrance.com/data/NXFR33_LFPW_.xml";

XDocument doc = XDocument.Load(url);
var selectedBook = from r in doc.Descendants("DV")
                          .Where(r => (string)r.Attribute("dep").Value == Departement)
                           select new
                           {
                               Color = r.Attribute("coul").Value,
                               Risque = (string) r.Element("risque").Attribute("val").Value,
                           };

And the XML looks like this:

<DV dep="02" coul="1"/>
<DV dep="03" coul="3">
    <risque val="6"/>
</DV>

Does anyone have an idea ?

2 Answers 2

1

The issue is that some DV elements don't have a child risque element, so in this part of your query:

Risque = (string) r.Element("risque").Attribute("val").Value

Element will return null, and you will get a null reference exception when you try to call Attribute.

You can fix this by making not going from sequence to single item until the end, and making use of the explicit conversions from elements and attributes to primitive types like string. This way, converting from attribute to string for a null attribute will just return null.

Risque = (string) r.Elements("risque").Attributes("val").SingleOrDefault()

See this fiddle for a working demo.

Sign up to request clarification or add additional context in comments.

4 Comments

Work great thank ! Do you know how to deal with multiple Risque node ? For example <DV dep="14" coul="2"><risque val="6"/><risque val="5"/> </DV>
@Hydro it would depend on how you want to deal with it. Do you want the first? Last? Highest? Lowest? Total? A list of all of them?
A list of all the risque value
@Hydro in that case, use r.Elements("risque").Attributes("val").Select(x => x.Value).ToList().
0

Try this

            XDocument doc = XDocument.Load(url);
            var selectedBook = doc.Descendants("DV")
                               .Where(r => (string)r.Attribute("dep") == Departement)
                               .Select(r => new {
                                   Color = r.Attribute("coul").Value,
                                   Risque = r.Element("risque") == null ? null : (string)r.Element("risque").Attribute("val").Value,
                               }).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.