如何将xml读入类中?

时间:2013-10-01 08:11:16

标签: c# xml serialization

我想将xml反序列化为c#。 但我收到错误,无法修复它。

错误是:

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

反序列化代码:

    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;
    }

课程是:

[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;
        }
    }
}

通过测试:

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

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

该异常将在线投放:

 result = serializer.Deserialize(reader);

为什么会这样?怎么解决这个问题?

1 个答案:

答案 0 :(得分:4)

<A vers="1.0" type="pd">不是XML。请参阅specs。您的根元素缺少其结束标记。

使您的文档看起来像这样:

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