0

I have the following XML name Sample.xml which I am trying to query accountNo with XDocument:

<Request xmlns="http://CompanyName.AppName.version1">
    <Person>
        <AccountNo>83838</AccountNo>
        <FirstName>Tom</FirstName>
        <LastName>Jackson</LastName>
    </Person>
    <Person>
        <AccountNo>789875</AccountNo>
        <FirstName>Chris</FirstName>
        <LastName>Smith</LastName>
    </Person>

Using below code in C# i am able to fetch Account no of first person

XDocument xmlDoc = XDocument.Load("Sample.xml");    
XNamespace nsSys = "http://CompanyName.AppName.version1";
XElement xEl2 = xmlDoc.Element(nsSys + "Request ");
XElement xEl3 = xEl2.Element(nsSys + "Person");
XElement xEl4 = xEl3.Element(nsSys + "AccountNo");
String sValue = xEl4.Value;

Ouput : 83838

How do you write code to extract account no of all person eg.

83838

789875
crthompson
  • 15,653
  • 6
  • 58
  • 80

1 Answers1

0

You can simply project the data using Select:-

XNamespace ns = "http://CompanyName.AppName.version1";
var AccountNumbers = xdoc.Descendants(ns + "Person")
                         .Select(x => (string)x.Element(ns + "AccountNo")).ToList();

This will give you all the AccountNumbers as List<String>.

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • Hi rahul last question how to modify the AccountNo value ? – alice toppo May 04 '15 at 10:47
  • @alicetoppo - You can use `SetElementValue` method, you need to fetch the particular XElement and apply this method. Finally save your Xdocument object. Please refer this answer :- http://stackoverflow.com/a/1487764/1529657 – Rahul Singh May 04 '15 at 11:11