<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,
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> .
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.
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.
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")
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With