tags:

views:

42

answers:

1

I'm trying to get values from xml, and I have problem with empty value. I'm using this query to get all not empty values from Attribute "RODZ", and this code works, but it return me empty values too :/

 XDocument loaded = XDocument.Load(@"c:\TERC.xml");

 var q = (from c in loaded.Descendants("catalog")
                     from r in c.Descendants("row")
                     select r.Descendants("col").Where(col1 =>
                            col1.Attribute(XName.Get("name")).Value ==
                            "RODZ").Where(kc => kc.ToString() != "").FirstOrDefault().Value ?? "0").ToList();

Tis is a big problem for me because I'm must parse all values to int, and this query doesn't work:

var q = (from c in loaded.Descendants("catalog")
                     from r in c.Descendants("row")
                     select int.Parse(r.Descendants("col").Where(col1 =>
                            col1.Attribute(XName.Get("name")).Value ==
                            "RODZ").Where(kc => kc.ToString() != "").FirstOrDefault().Value ?? "0")

                  ).ToList();

I want to get 0 when the value is null, because I later convert it to Enum.

Do you see what's work with this code?

<?xml version="1.0" encoding="UTF-8" ?> 
 <teryt>
 <catalog name="Compix">
 <row>
    <col name="NAME">Name1</col> 
    <col name="ID"/>
    </row>
 <row>
    <col name="NAME">Name2</col> 
    <col name="ID">1</col> 
    </row>
 <row>
    <col name="NAME">Name3</col> 
    <col name="RODZ">2</col> 
    </row>  
</catalog>
</teryt>
+1  A: 

Your problem is in this bit:

 where(kc => kc.ToString() != "")

change it to:

 where(kc => !string.IsEmptyOrNull(kc.Value))
Aliostad
I see :) but now FirstOrDefault().Value gives me exceptiom, when value is null. I'm not good with linq :/
Updated. Use IsEmptyOrNull.
Aliostad