Search code examples
c#soapsoapuixelement

How to access this nested XElement?


hopefully you can help, this is the SOAP response message that I'm trying to read data from:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <GetVehicleImageDocDescriptorsResponse xmlns="http://kyle/webservices/">
         <GetVehicleImageDocDescriptorsResult>
            <VehicleImageDocDescriptor>
               <Id>91222</Id>
               <Epoch>2014-09-12T16:46:22.643</Epoch>
               <ImageSetId>172308</ImageSetId>
               <ImageMetadata>
                  <Group>public</Group>
                  <POV>Beauty Master</POV>
                  <RightHandDrive>false</RightHandDrive>
                  <ImageHashCode>1123</ImageHashCode>
               </ImageMetadata>
            </VehicleImageDocDescriptor>
            <VehicleImageDocDescriptor>
               <Id>123</Id>
               ...REPEATING....

And this is the code snippet I have to access the values in those fields:

XDocument doc = XDocument.Parse(getVehicleImageDocDescriptorsResult);
XNamespace ns = "http://kyle/webservices/";
IEnumerable<XElement> responses = doc.Descendants(ns + "VehicleImageDocDescriptor");


foreach (XElement response in responses)
{
    pov = (string)response.Element(ns + "POV");
    epoch = (string)response.Element(ns + "Epoch");
    imageSetId = (string)response.Element(ns + "ImageSetId");
    parsedDate = DateTime.Parse(epoch);
}
                

This works for 'epoch', 'imageSetId' but doesn't work for 'pov', I'm assuming because the 'pov' field is indented another level down it needs an extra level of 'address' if you would, I've been trying different ideas for hours and can't seem to retrieve the value, I've even tried having the full namespace as variable and using that in the 'pov's 'element' bracket but that doesn't work either.

Can anyone please provide me with some ideas?

Many thanks, Kyle.


Solution

  • In that XML of yours, the POV is nested within ImageMetadata. This should work:

    foreach (XElement response in responses)
    {
        var imageMetadata = response.Element(ns + "ImageMetadata");
        var pov = (string)imageMetadata.Element(ns + "POV");
    
        var epoch = (string)response.Element(ns + "Epoch");
        var imageSetId = (string)response.Element(ns + "ImageSetId");
        var parsedDate = DateTime.Parse(epoch);
    }