Rocketq
Rocketq

Reputation: 5791

How properly work with LINQ to XML?

I have generated such xml file

 <?xml version="1.0" encoding="utf-8"?>
<Requestes>
  <Single_Request num="1">
    <numRequest>212</numRequest>
    <IDWork>12</IDWork>
    <NumObject>21</NumObject>
    <lvlPriority>2</lvlPriority>
    <NumIn1Period>21</NumIn1Period>
  </Single_Request>
</Requestes>

My aim is to get IDWork,numRequest and etc elements. I tried to get them this way:

foreach (XElement el in doc.Root.Elements())
  {
   if (el.Name == "Single_Request") 
       {
          string num = el.Elements("numRequest").Value;  
// but he says, that he cant do this  .Value because it doest exist at all  
       }          
    }

How to fix this?

Upvotes: 3

Views: 55

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

You have this error, because Elements("numRequest") returns collection of elements, not single element. You should use Element("numRequest") instead.

Also I suggest you to use query for getting elements by name instead of enumerating all elements and verifying their names:

var request = doc.Root.Element("Single_Request");
var num = (int)request.Element("numRequest");

Usually you use anonymous types or custom objects to group values parsed from xml:

var query = from r in doc.Root.Elements("Single_Request")
            where (int)r.Attribute("num") == 1 // condition
            select new {
                NumRequest = (int)request.Element("numRequest"),
                IdWork = (int)request.Element("IDWork"),
                NumObject = (int)request.Element("NumObject")
            };

var request = query.SinlgleOrDefault();
// use request.IdWork

Upvotes: 2

Related Questions