lookitskris
lookitskris

Reputation: 678

Parse XML response and return collection of objects

I have found many different examples of how to parse an XML file and most get me part of the way there but I cannot find an example that works how I need it to.

Given the following XML response

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ParentNode xmlns="http://my.own.namespace.com/">
      <ChildNode>
        <Value1>string<Value1>
        <Value2>string<Value2>
      </ChildNode>
       <ChildNode>
        <Value1>string<Value1>
        <Value2>string<Value2>
      </ChildNode>
    </ParentNode>
  </soap:Body>
</soap:Envelope>

How do I return a collection of ChildNode objects populated with the values from Value1 and Value2?

The furthest I have got so far is to get a list of all the Value1 strings like so

var soap = XDocument.Parse(response);
XNamespace ns = XNamespace.Get("http://my.own.namespace.com/");

var objectList = soap.Decendents(ns + "ParentNode");
    .Select(x => x.Elements().First.Value).ToList();

I also tried to use the XSD tool but this gave an error that http://my.own.namespace.com/:ParentNode could not be found.

Thank you for any help, I'm sure this is a very easy problem to solve

Upvotes: 2

Views: 1437

Answers (2)

Thirisangu Ramanathan
Thirisangu Ramanathan

Reputation: 614

It works :

 XNamespace ns1 = XNamespace.Get("http://my.own.namespace.com/");

 var values = from childnode in xx.Descendants(ns1 + "ParentNode").Elements(ns1 + "ChildNode")
                          select new
                          {
                              Value1 = (string)childnode.Element(ns1 + "Value1"),
                              Value2 = (string)childnode.Element(ns1 + "Value2"),
                          };

Upvotes: 0

har07
har07

Reputation: 89315

Try this way :

XNamespace ns = XNamespace.Get("http://my.own.namespace.com/");

var objectList = soap.Decendents(ns + "ParentNode");
                     .Select(x => new ChildNode
                                  {
                                    Value1 = (string)x.Element(ns+"Value1"),
                                    Value2 = (string)x.Element(ns+"Value2"),
                                  }
                              )
                      .ToList();

I assume you have ChildNode class defined containing two properties of type string: Value1 and Value2.

Upvotes: 1

Related Questions