2013-10-01 27 views
0

我想將xml反序列化爲c#。 但我收到錯誤,無法修復它。如何將xml讀入類?

錯誤是:

"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); 

爲什麼發生這種情況?如何解決這個問題?

+0

你可以包括你的XML的片段? – psubsee2003

+0

您是否嘗試過僅在您的課堂上使用[System.Serializable()]? – Shide

回答

4

<A vers="1.0" type="pd">不是XML。請參閱specs。您的根元素缺少結束標記。

讓您的文檔是這樣的:

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