Search code examples
c#jsonxmlxml-parsingdeserialization

Parse Xml text to class in c#


I want to parse below xml text to object of class

xml :

<?xml version="1.0" encoding="UTF-8"?><data><Error><![CDATA[No Error]]></Error></data>

class :

        public class AAA
        {
            public BBB data;
        }

        public class BBB
        {
            public string Error;
        }

Code :

XmlSerializer serializer = new XmlSerializer(typeof(DUserInfo));
                        using (StringReader reader = new StringReader(xmlText))
                        {
                            AAA info = (AAA)(serializer.Deserialize(reader));
                        }//using

Error :

There is an error in XML document (1, 40).
<data xmlns=''> was not expected.

Solution

  • {
    "?xml": {
        "@version": "1.0",
        "@encoding": "UTF-8"
    },
    "data": {
        "Error": {
            "#cdata-section": "No Error"
        }
    }
    }
    

    is JSON not XML, So You have deserialize as JSON (not as XML) to Object.

    Use NewtonSoft.Json dll to parse this text format.

    Alternatively... :

    Or you can convert your JSON to an actual valid xml first and then convert it to object.

    Also you can try some online JSON-to-XML converter :
    (pass the result to AAA info = (AAA)(serializer.Deserialize(reader));)

    Example result from : http://www.utilities-online.info/xmltojson/#.WCVnky2LQrg

    <?xml version="1.0" encoding="UTF-8" ?>
        <?xml>
            <@version>1.0</@version>
            <@encoding>UTF-8</@encoding>
        </?xml>
        <data>
            <Error>
                <#cdata-section>No Error</#cdata-section>
            </Error>
        </data>
    

    PS: Please check your class structures too.

    Correct Json will be.

    <?xml version="1.0" encoding="UTF-8"?>
    <data>
        <Error>
            <cdata-section>No Error</cdata-section>
        </Error>
    </data>
    

    You classes will be like this.

    [XmlRoot(ElementName="Error")]
    public class Error {
        [XmlElement(ElementName="cdata-section")]
        public string Cdatasection { get; set; }
    }
    
    [XmlRoot(ElementName="data")]
    public class Data {
        [XmlElement(ElementName="Error")]
        public Error Error { get; set; }
    }
    

    You can desialize your xml to object in this way.

    string xmlText = "your xml";
    XmlSerializer serializer = new XmlSerializer(typeof(Data));
        using (StringReader reader = new StringReader(xmlText))
        {
            Data info = (Data)(serializer.Deserialize(reader));
        }
    

    You are doing in wrong way in this line.

    XmlSerializer serializer = new XmlSerializer(typeof(DUserInfo));