0

我想将 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);

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

4

1 回答 1

4

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

使您的文档如下所示:

<A vers="1.0" type="pd"></A>
于 2013-10-01T08:28:27.013 回答