Deserialize an xml file or parse using linq to xml

Joe Ruder

Simplified XML file I need to decode:

    <?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:deliverylistResponse xmlns:ns2="http://tdriverap3.wsbeans.iseries/">
         <return>
            <COUNT>3</COUNT>
            <DELIVERIES>
               <ADD1>1300 address 1</ADD1>
               <CITY>NICE CITY</CITY>
               <ZIP>85705</ZIP>
            </DELIVERIES>
            <DELIVERIES>
               <ADD1>40 S PINAL PKWY AVE</ADD1>
               <CITY>FLORENCE</CITY>
               <ZIP>85132</ZIP>
            </DELIVERIES>
            <DELIVERIES>
               <ADD1>1825 EAST MAIN</ADD1>
               <CITY>CHANDLER</CITY>
               <ZIP>85286</ZIP>
            </DELIVERIES>
            <ERRORCODE/>
            <RUNDATE>09/26/2018</RUNDATE>
         </return>
      </ns2:deliverylistResponse>
   </soap:Body>
</soap:Envelope>

I am using the following to try and decode each of the individual addresses in the code.

I cannot figure out how to access them.

XElement xelement = XElement.Load(@"e:\test\X2.xml");
        IEnumerable<XElement> addresses = xelement.Elements();

        foreach (var address in addresses)
        {
            Console.WriteLine(address);
            Console.WriteLine(address.Element("CITY").Value);

        }

The first writeline works (it outputs the entire XML tree), the second says "System.Xml.Linq.XContainer.Element(...) returned null" - I have tried using DELIVERIES, COUNT, Body etc...

Obviously I am not telling it correctly how to traverse the structure, but I do not know how to go any further with it..

UPDATE: Thanks to some help I have figured out how to do it using Linq. I would still like to be able to deserialize it if anybody has a pointer. I followed several tutorials, but the multiple levels of this XML seems to be throwing me off.

I have created a class to hold the data but that is as far as my success with that path has gone.

Thank you, Joe

Joe Ruder

Thank you Crowcoder -- this is what I wound up with, which will work. The real XML file however does have about 60 fields so this is not as good as using a deserialize routine but I can at least move forward with the project.

XElement xelement = XElement.Load(@"e:\test\x2.xml");

            IEnumerable<XElement> textSegs =
                 from seg in xelement.Descendants("DELIVERIES")
                  select seg;

            foreach (var address in textSegs)
            {
                Console.WriteLine(address.Element("ADD1").Value);
                Console.WriteLine(address.Element("CITY").Value);
                Console.WriteLine(address.Element("ZIP").Value);

            }


            Console.ReadKey();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related