简体   繁体   中英

How to read xml into class?

I want to deserialize xml into c#. But I am getting error and cannot fix it.

Error is:

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

Deserialize code:

    public static object XmlDeserializeFromString(string objectData, Type type)
    {
        var xmlAttributes = new XmlAttributes();
        var xmlAttributeOverrides = new XmlAttributeOverrides();

        xmlAttributes.Xmlns = false;
        xmlAttributeOverrides.Add(typeof(A10), xmlAttributes);


        var serializer = new XmlSerializer(type, xmlAttributeOverrides);
        object result=null;

        try
        {
            using (TextReader reader = new StringReader(objectData))
            {
                result = serializer.Deserialize(reader);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        return result;
    }

The class is:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "A-1.0", Namespace = "")]
[System.Xml.Serialization.XmlRootAttribute("A", Namespace = "", IsNullable = false)]  
public  class A10
{

    private string versField;

    private string typeField;

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }
}

And testing by:

   string xml = "<A vers=\"1.0\" type=\"pd\">";

   A10 a = (A10) XmlDeserializeFromString(xml, typeof(A10));

The exception is thrown on line:

 result = serializer.Deserialize(reader);

Why this is happening? How to solve this?

<A vers="1.0" type="pd"> is not XML. See the specs . Your root element is missing its closing tag.

Make your document look like this:

<A vers="1.0" type="pd"></A>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM