Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data from XNode

Tags:

c#

xml

linq

How can I read data from XNode.

Here is my XNode I got from another query.

<claim kind="national" sequence="1">
  <country>UK</country>
  <number>66</number>
  <date>20080602</date>
</claim>
<claim kind="national" sequence="3">
  <country>TH</country>
  <number>61</number>
  <date>20090316</date>
</claim>

I want to get the country and date value.

Any help would be really appreciated. Thanks.

like image 645
kevin Avatar asked Jul 25 '26 14:07

kevin


2 Answers

Try,

var list = from ele in XDocument.Load(@"c:\file.xml").Descendants("claim")
           select new
            {
              Country=(string)ele.Element("country"),
              Date=(string)ele.Element("date")
             };
 foreach (var t in list)
 {
    Console.WriteLine(t.Country + " "+ t.Date );
 }

EDIT:

string country=(string)((XElement)xNodeObj).Element("country");
like image 81
KV Prajapati Avatar answered Jul 27 '26 02:07

KV Prajapati


Here is a way to do it using XPath:

string xml = "<main><claim kind=\"national\" sequence=\"1\"> <country>UK</country> <number>66</number>  <date>20080602</date></claim><claim kind=\"national\" sequence=\"3\">  <country>TH</country>  <number>61</number>  <date>20090316</date></claim></main>";
XDocument doc = XDocument.Parse(xml);
doc.XPathSelectElement("//claim[country = 'TH']/number").Value.Dump("xpath stuff");
like image 44
AlexIIP Avatar answered Jul 27 '26 02:07

AlexIIP



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!