tags:

views:

96

answers:

2

hi. i have the following xml

<students>
  <student>
    <id>12</id>
    <name>Mohsan</name>
  </student>
  <student>
    <id>2</id>    
  </student>
  <student>
    <id>3</id>
    <name>Azhar</name>
  </student>
</students>

note that in 2 name element is missing.

i have to read this xml using Linq to XML

i used following code to get all students..

please suggest me improvement in this code

var stds = from std in doc.Descendants("student")
                select new
                {
                    ID = std.Element("id").Value,
                    Name = (std.Element("name")!=null)?std.Element("name").Value:string.Empty
                };
+3  A: 

Syntax with 'let' allows you avoid twice ask Element("name")

var stds = from std in doc.Descendants("student")
            let elName = std.Element("name") 
            select new
            {
                ID = std.Element("id").Value,
                Name = (elName!=null)?elName.Value:string.Empty
            };
Dewfy
can i use ?? for this. it is giving me error. Name = std.Element("name")??string.Empty
Mohsan
@Mohsan std.Element("name")?? - resolve XML element, but not string, on other hand string.Empty is a string, so it is type incompatibility. Unfortunately std.Element("name").ToString() ?? will also fail since NullPointerException.
Dewfy
+1  A: 

You can use the fact that there's an explicit conversion from XElement to string, which returns null for a null XElement reference. You can then use the null-coalescing operator to go from null to an empty string:

var stds = from std in doc.Descendants("student")
           select new
           {
               ID = std.Element("id").Value,
               Name = (string) std.Element("name") ?? "";
           };
Jon Skeet
hmmmm. good choices
Mohsan