We help IT Professionals succeed at work.

XML to Class Object C#

sbornstein2
sbornstein2 asked
on
<?xml version="1.0" encoding="UTF-16"?>
<cust-response>
   <result-response>
     <load entity="CUSTOMER" id="1234">
        <result-entry result-id="456" succeed="Yes">
           <return F_RESULT="focused" STATUS="C" />
        </result-entry>
        <result-entry result-id="789" succeed="No">
           <errors>
              <error name="other">
                 <desc>
                      <error-message>Result cannot be validated</error-message>
                 </desc>
              </errors>
        </result-entry>
     </load>
     <load entity="CUSTOMER" id="5678">
        <result-entry result-id="789" succeed="Yes">
           <return F_RESULT="focused" STATUS="C" />
        </result-entry>
        <result-entry result-id="555" succeed="No">
           <errors>
              <error name="other">
                 <desc>
                      <error-message>Result cannot be validated</error-message>
                 </desc>
              </errors>
        </result-entry>
     </load>
   </result-response>
</cust-response>

I want to return a class array of the following:
   CustomerId
      Result-id's and succeed yes or no and if errors showing the error messages
Comment
Watch Question

Chief Technology Ninja
Distinguished Expert 2019
Commented:
You can use Generic serialization, I wrote sample signatures of such a class long back but it still works.

You can get more details from here: https://crmxpress.net/blog/2008/12/generic-serializer-deserializer/
public static T Deserialize<T>(
string serializedData
)
{
//check whether the incoming data is not a null string
if (string.IsNullOrEmpty(serializedData))
return default(T); //This can be controversial, so handle with care and as per your requirements, in certain cases you can return null as well, kindly let me know if you have anything that can improvise this code

//create a serializer
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
//Use the deserializer we have just created and deserialize the object.
}

Open in new window

Most Valuable Expert 2011
Top Expert 2015

Commented:
This is not valid XML. Is that a typo? (You're missing a closing </error> tag in a couple of places.)

Once you iron out the structure, you can use the XSD tool to generate a class file that matches this XML structure:


If you don't have an XSD file to start with, you can use the XSD tool to infer a schema from the XML. Just execute:

xsd.exe your.xml

The tool will output an XSD file of the same name (different extension). You can then pass that XSD into the tool as described in the linked article.