2

I have this SOAP message and I need to serialize into a C# Object:

<SOAP-ENV:Envelope xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema" xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <SOAPSDK4:GetStoreInformationResponse xmlns:SOAPSDK4="http://www.example.com/message/">
      <StoreInformation>
        <StoreID>99612</StoreID>
        <BusinessDate>2016-01-28</BusinessDate>
        <Address type="Address-US">
           <Street>Via Roma 1</Street>
           <City>Milano</City>
        </Address>
      </StoreInformation>
    </SOAPSDK4:GetStoreInformationResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I found many example of serialization, but I can not apply these to my case. Someone can help me?

This is the c# class generated:

//------------------------------------------------------------------------------
// <auto-generated>
//     Il codice è stato generato da uno strumento.
//     Versione runtime:4.0.30319.42000
//
//     Le modifiche apportate a questo file possono provocare un comportamento non corretto e andranno perse se
//     il codice viene rigenerato.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// Codice sorgente generato automaticamente da xsd, versione=4.0.30319.33440.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.example.com/message/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.example.com/message/", IsNullable = false)]
public partial class GetStoreInformationResponse
{

    private GetStoreInformationResponseStoreInformation storeInformationField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public GetStoreInformationResponseStoreInformation StoreInformation
    {
        get
        {
            return this.storeInformationField;
        }
        set
        {
            this.storeInformationField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.example.com/message/")]
public partial class GetStoreInformationResponseStoreInformation
{

    private string storeIDField;

    private string businessDateField;

    private GetStoreInformationResponseStoreInformationAddress[] addressField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string StoreID
    {
        get
        {
            return this.storeIDField;
        }
        set
        {
            this.storeIDField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string BusinessDate
    {
        get
        {
            return this.businessDateField;
        }
        set
        {
            this.businessDateField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Address", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public GetStoreInformationResponseStoreInformationAddress[] Address
    {
        get
        {
            return this.addressField;
        }
        set
        {
            this.addressField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.example.com/message/")]
public partial class GetStoreInformationResponseStoreInformationAddress
{

    private string streetField;

    private string cityField;

    private string typeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Street
    {
        get
        {
            return this.streetField;
        }
        set
        {
            this.streetField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string City
    {
        get
        {
            return this.cityField;
        }
        set
        {
            this.cityField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Davide Nobili
  • 49
  • 1
  • 4

2 Answers2

1

You can try xsd.exe tool to generate C# class, and the use this piece of code :

    /// <summary>
    /// Methode de deserialisation d'objets
    /// </summary>
    /// <param name="xmlObject">Document XML à désérialiser</param>
    /// <returns>Retourne l'objet chargé avec les données du document XML passé en paramètres</returns>
public static ObjectTypeT Deserialize(XmlDocument xmlObject)
{
    if (xmlObject == null)
        throw new NullXmlDocumentException();
    if (xmlObject.DocumentElement == null)
        throw new NullXmlDocumentElementException();

    using (XmlNodeReader reader = new XmlNodeReader(xmlObject.DocumentElement))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(ObjectTypeT));
        return (ObjectTypeT)serializer.Deserialize(reader);
    }
}

to generate your object. You first have to load the Xml in a XmlDocument.

Rom Eh
  • 1,981
  • 1
  • 16
  • 33
  • Thank you, but I receive this error when call "return (GetStoreInformationResponse)serializer.Deserialize(reader);": Error in XML document. The inner exception is: unexpected – Davide Nobili Jul 13 '16 at 13:05
  • Can you post the generated C# class ? – Rom Eh Jul 13 '16 at 13:20
  • See my anser below ;) – Davide Nobili Jul 13 '16 at 15:00
  • 1
    Ok, You don't have the envelope in your C#. By the way, you can just select GetStoreInformationResponse in your XmlDocument and create a new XmlDocument by adding only the content of the element. – Rom Eh Jul 13 '16 at 16:07
1

Try code below. I used Load(string FILENAME), but you can also use Parse(string XML)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var StoreInformation = doc.Descendants().Where(x => x.Name.LocalName == "StoreInformation").Select(y => new {
                storeID = (string)y.Elements().Where(z => z.Name.LocalName == "StoreID").FirstOrDefault(),
                businessDate = (DateTime)y.Elements().Where(z => z.Name.LocalName == "BusinessDate").FirstOrDefault(),
                type = (string)y.Elements().Where(z => z.Name.LocalName == "Address").Select(a => a.Attribute("type")).FirstOrDefault(),
                street = (string)y.Elements().Where(z => z.Name.LocalName == "Address").Select(a => a.Element(a.Name.Namespace + "Street")).FirstOrDefault(),
                city = (string)y.Elements().Where(z => z.Name.LocalName == "Address").Select(a => a.Element(a.Name.Namespace + "City")).FirstOrDefault()
            }).ToList();

        }
    }
 }
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Thanks, a bit uncomfortable with large structures, but works – Davide Nobili Jul 13 '16 at 13:06
  • 5 items in a structure is large? I made code very robust because of the namespaces which made the statements kind of long. – jdweng Jul 13 '16 at 13:24
  • Yes, 5 items are very few, but I need to use the same logic also with large structures, not only with that in example ;) – Davide Nobili Jul 13 '16 at 14:53
  • You can get tags recursively out of xml using code. See posting : http://stackoverflow.com/questions/28976601/recursion-parsing-xml-file-with-attributes-into-treeview-c-sharp – jdweng Jul 13 '16 at 15:44