Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq To Xml Null Checking of attributes

<books>
   <book name="Christmas Cheer" price="10" />
   <book name="Holiday Season" price="12" />
   <book name="Eggnog Fun" price="5" special="Half Off" />
</books>

I'd like to parse this using linq and I'm curious what methods other people use to handle special. My current way of working with this is:

var books = from book in booksXml.Descendants("book")
                        let Name = book.Attribute("name") ?? new XAttribute("name", string.Empty)
                        let Price = book.Attribute("price") ?? new XAttribute("price", 0)
                        let Special = book.Attribute("special") ?? new XAttribute("special", string.Empty)
                        select new
                                   {
                                       Name = Name.Value,
                                       Price = Convert.ToInt32(Price.Value),
                                       Special = Special.Value
                                   };

I am wondering if there are better ways to solve this.

Thanks,

  • Jared
like image 914
Howel Avatar asked Dec 02 '10 15:12

Howel


People also ask

How to Check null value in Xml?

In an XML document, the usual way to represent a null value is to leave the element or attribute empty. Some business messages use a special value to represent a null value: <price>-999</price> .

Is null in LINQ?

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.


2 Answers

In C# 6.0 you can use monadic Null-conditional operator ?. After applying it in your example it would look like this:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = book.Attribute("name")?.Value ?? String.Empty,
                Price = Convert.ToInt32(book.Attribute("price")?.Value ?? "0"),
                Special = book.Attribute("special")?.Value ?? String.Empty
            };

You can read more here in part titled Null-conditional operators.

like image 190
Krzysztof Branicki Avatar answered Nov 15 '22 17:11

Krzysztof Branicki


You can cast the attribute to a string. If it is absent you will get null and subsequent code should check for null, otherwise it will return the value directly.

Try this instead:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = (string)book.Attribute("name"),
                Price = (string)book.Attribute("price"),
                Special = (string)book.Attribute("special")
            };
like image 36
Ahmad Mageed Avatar answered Nov 15 '22 18:11

Ahmad Mageed