CM99
CM99

Reputation: 313

XML - where node has same name but different values

I am trying to read an xml file (and later import the data in to a sql data base) which contains employees names address' etc. The issue I am having is that in the xml the information for the address for the employee the node names are all the same.

<Employee>
 <EmployeeDetails>
   <Name>
     <Ttl>Mr</Ttl>
     <Fore>Baxter</Fore>
     <Fore>Loki</Fore>
     <Sur>Kelly</Sur>  
   </Name>
   <Address> 
     <Line>Woof Road</Line>
     <Line>Woof Lane</Line>
     <Line>Woofington</Line>
     <Line>London</Line> 
   </Address>   
    <BirthDate>1985-09-08</BirthDate>   
    <Gender>M</Gender>
    <PassportNumber>123756rt</PassportNumber>   
    </EmployeeDetails>
</Employee>

I all other items are fine to extract and I have tried to use Linq to iterate through each "Line" node but it always just gives be the first Line and not the others.

 var xAddreesLines = xEmployeeDetails.Descendants("Address").Select(x => new
   {
     address = (string)x.Element("Line").Value

   });
     foreach (var item in xAddreesLines)
       {
          Console.WriteLine(item.address);
       }

I need to able to when I'm importing to my sql db that address line is separate variable
eg

var addressline1 = first <line> node

var addressline2 = second <line> node etc etc.

Any advice would be most welcome.

Upvotes: 0

Views: 3652

Answers (2)

usamazf
usamazf

Reputation: 3215

You can do it like this:

using System.Xml;
            .
            .
            .
            XmlDocument doc = new XmlDocument();
            doc.Load("source.xml");
            // if you have the xml in a string use doc.LoadXml(stringvar)
            XmlNamespaceManager nsmngr = new XmlNamespaceManager(doc.NameTable);
            XmlNodeList results = doc.DocumentElement.SelectNodes("child::Employee", nsmngr);
            foreach (XmlNode result in results)
            {
                XmlNode namenode = result.SelectSingleNode("Address");
                XmlNodeList types = result.SelectNodes("line");
                foreach (XmlNode type in types)
                {
                    Console.WriteLine(type.InnerText);
                }
                XmlNode fmtaddress = result.SelectSingleNode("formatted_address");
            }

Refer to this question for the original source.

Upvotes: 1

Rahul Singh
Rahul Singh

Reputation: 21825

This should give you the expected output:-

var xAddreesLines = xdoc.Descendants("Address")
                        .Elements("Line")
                        .Select(x => new { address = (string)x });

You need to simply fetch the Line elements present inside Address node and you can project them. Also note there is no need to call the Value property on node when you use explicit conversion.

Upvotes: 2

Related Questions