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 Answer 1

1

Your problem is in this bit:

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

change it to:

 where(kc => !string.IsEmptyOrNull(kc.Value))
Sign up to request clarification or add additional context in comments.

1 Comment

I see :) but now FirstOrDefault().Value gives me exceptiom, when value is null. I'm not good with linq :/

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.