Using Linq to get XML data from database

71 views Asked by At

I'm struggling to get the values of a single xml node using Linq.

Here is my XML.

       <?xml version="1.0" encoding="utf-8"?>
       <record>
       <AddressLine1>abcd street</AddressLine1>
       <AddressLine2>xyz AVE</AddressLine2>
       <AddressCity>Illinois</AddressCity>
       <AddressState>Chicago</AddressState>
       <AddressZip>23434</AddressZip>
       </record>

And here is my c# code

    XElement xmlDoc = XElement.Parse(varQ.Content);
       //When I debug I find that xmlDoc contains the XML. So that is alright.

    var q = (from lpi in xmlDoc.Descendants("record")
            select new { AddressLine1 = lpi.Element("AddressLine1").Value,
            AddressLine2 = lpi.Element("AddressLine2").Value,
            AddressCity = lpi.Element("AddressCity").Value,
            AddressCountry = lpi.Element("AddressCountry").Value,
            AddressState = lpi.Element("AddressState").Value,
            AddressZip = lpi.Element("AddressZip").Value,
            }).FirstOrDefault();

var q shows null. Can u please help me find out what is wrong here?

1

There are 1 answers

5
FoggyFinder On BEST ANSWER

Replace Descendants on DescendantsAndSelf:

 string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
       <record>
       <AddressLine1>abcd street</AddressLine1>
       <AddressLine2>xyz AVE</AddressLine2>
       <AddressCity>Illinois</AddressCity>
       <AddressState>Chicago</AddressState>
       <AddressZip>23434</AddressZip>
       </record>";

            XElement xmlDoc = XElement.Parse(xml);
            var q = (from lpi in xmlDoc.DescendantsAndSelf("record")
                     select new
                     {
                         AddressLine1 = (string)lpi.Element("AddressLine1"),
                         AddressLine2 = (string)lpi.Element("AddressLine2"),
                         AddressCity = (string)lpi.Element("AddressCity"),
                         AddressCountry = (string)lpi.Element("AddressCountry"),
                         AddressState = (string)lpi.Element("AddressState"),
                         AddressZip = (string)lpi.Element("AddressZip"),
                     }).FirstOrDefault();
            Console.WriteLine(q);

Print:

{ AddressLine1 = abcd street, AddressLine2 = xyz AVE, AddressCity = Illinois, AddressCountry = , AddressState = Chicago, AddressZip = 23434 }

Link: https://dotnetfiddle.net/fXQivX