如何将 xml 读入类

本文关键字:xml | 更新日期: 2023-09-27 18:33:29

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

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

如何将 xml 读入类

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

使文档如下所示:

<A vers="1.0" type="pd"></A>
相关文章:
  • 没有找到相关文章