Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get root node attribute value using linq

Tags:

c#

linq-to-xml

I have the following XML. How to read the root node attribite value and it's decendents using LINQ? I am trying to read "dId" and "dTime" from root node, "id" from Customer element and Order number.

<?xml version="1.0" encoding="utf-8" ?>
 <Customers dId="wqwx" dTime="10-9-09 11:23">
   <Customer id="1">
      <Orders>
        <Order number="22" status="ok">
      </Orders>
   </Customer>
 </Customers>

I tried the following code but it doesn't work.

XDocument doc= XDocument.Load(@"C:\Customers.xml");
var q = from c in doc.Descendants("Customers")
        select new        
          {   
           dID = c.Attribute("dId"),
           dTime = c.Attribute("dTime");
          }

2 Answers

first, fix your xml (<Order .... />) then, your linq should look like this....

// .Elements(...) selects all elements of type "Customer"
    var q = from c in xDoc.Elements("Customers") 
    select new
    {
        dID = c.Attribute("dId"), 
        dTime = c.Attribute("dTime")
    }; 

you should dl LinqPad... it lets you do Linq queries on the fly, even agains SQL databases. Then, once you get the results you want, copy and past your linq into your source code.

like image 79
Muad'Dib Avatar answered May 11 '26 09:05

Muad'Dib


You have to end the order tag with: />

xDoc.Descendants("Customers") should work as well as xDoc.Elements("Customers").

Chris, is there a specific advantage to using .Elements?

like image 32
Patrick Karcher Avatar answered May 11 '26 09:05

Patrick Karcher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!