Marios Nikolaou
Marios Nikolaou

Reputation: 1336

LINQ parse xml file and get values from specific nodes

I have an xml file and i try to retrieve data from specific nodes.But there are nodes that are missing, so i want to return empty string.Below is an example of my code, i am using LINQ.

string xml = @"<root>
                <employee>
                 <name>Val1</name>
                 <age>30</age>
                </employee>
                <employee>
                 <name>Val1</name>
                 <age>30</age>
                 <position>Priest</position>
                </employee>
               </root>";             

   XElement x = XElement.Parse(xml);
   IEnumerable<XElement> details = x.Elements();
   var valLst = (from el in details 
                 where el.Element("name").Value.Equals("Val1") 
                 select el.Value).ToList();

Details object contains the 2 employee nodes with their child nodes, so i want to take the child nodes values based on name node value.Also, i want to return empty string for the nodes that are missing (in example the position node is missing from the first section but exist in the second)

Thanks in advance.

Upvotes: 1

Views: 207

Answers (2)

Joe B
Joe B

Reputation: 788

this will give you an of IEnumerable<AnonymousType>

             var valLst =(from el in details 
             select new
             {
                 Name = el.Element("name").Value,
                 Position = el.Element("position")?.Value ?? ""
             });

Output:

      "{ Name = Val1, Position =  }"
      "{ Name = Val1, Position = Priest }"`

Upvotes: 0

T.S.
T.S.

Reputation: 19394

Here is your working example. You can go from here

string xml = @"<root>
            <employee>
             <name>Val1</name>
             <age>30</age>
            </employee>
            <employee>
             <name>Val1</name>
             <age>30</age>
             <position>Priest</position>
            </employee>
           </root>";             

XElement x = XElement.Parse(xml);
IEnumerable<XElement> details = x.Elements();
var valLst = (from el in details 
             let pos = (el.Element("position") == null ? string.Empty : el.Element("position").Value)
             where el.Element("name").Value.Equals("Val1") 
             select new {n = el.Value, p = pos}).ToList();

Console.WriteLine(valLst[0].n + " - " + valLst[0].p);
Console.WriteLine(valLst[1].n + " - " + valLst[1].p);

output:

Val130 -
Val130Priest - Priest

Upvotes: 1

Related Questions