xsd2code

Retrieving XML data and XmlSerializer


I have started using Xsd2Code and to date have been deserializing XML straight from an actual file. What I need to do now is deserialize the xml from a local variable.

Here's a code snippet.

using (FileStream getResponseDataFromFile = new FileStream   (@:\Temp\Output\DeclarationResponse.xml", FileMode.Open))
 {
            XmlSerializer serializeGbResponseXML = new XmlSerializer(typeof(declarationGbResponse));               
            declarationGbResponse myResponse = (declarationGbResponse)serializeGbResponseXML.Deserialize(getResponseDataFromFile);
foreach (var acceptanceResponseItem in myResponse.acceptanceResponse)   
{
........

 }

What I need to do is replace loading the XML from a FileSteam c:\temp... and instead parse it from a local variable then deserialize it from that variable. I can then use the class created by Xsd2Code and display and use the various properties.


Solution

  • This will work for you as long as "payloadXML" is a well formed xml string.

       public myType DeserializeEstimatePayload(string payloadXML)
        {
            myType est = null;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(myType ));
            MemoryStream memStream = new MemoryStream(Encoding.Unicode.GetBytes(payloadXML));
            est = (myType )xmlSerializer.Deserialize(memStream);
            xmlSerializer = null; memStream = null;
    
            return est;
        }