无法从XML反序列化

时间:2012-05-23 16:01:12

标签: c# xml serialization

我有一个固定的,有效的XML文档。我正在尝试反序列化它以获得对象层次结构。然而,抛出了一个例外。

这是我的XML文档:

<ROWSET>
   <ROW>
      <LOT>LOT1234</LOT>
      <DATE_TRANS>2012-05-20</DATE_TRANS>
      <NUMERO_AA227>AA227_001</NUMERO_AA227>
      <NUMERO_ETUI>ETUI_001</NUMERO_ETUI>   
      <IDENTITE_BOITE_1>Boite1_1</IDENTITE_BOITE_1>
      <IDENTITE_BOITE_2>Boite1_2</IDENTITE_BOITE_2>
      <IDENTITE_BOITE_3>Boite1_3</IDENTITE_BOITE_3>
      <IDENTITE_BOITE_4>Boite1_5</IDENTITE_BOITE_4>
      <IDENTITE_BOITE_5>Boite1_5</IDENTITE_BOITE_5>
   </ROW>
   <ROW>
      <LOT>LOT5678</LOT>
      <DATE_TRANS>2012-05-20</DATE_TRANS>
      <NUMERO_AA227>AA227_001</NUMERO_AA227>
      <NUMERO_ETUI>ETUI_001</NUMERO_ETUI>   
      <IDENTITE_BOITE_1>Boite1_1</IDENTITE_BOITE_1>
      <IDENTITE_BOITE_2>Boite1_2</IDENTITE_BOITE_2>
      <IDENTITE_BOITE_3>Boite1_3</IDENTITE_BOITE_3>
      <IDENTITE_BOITE_4>Boite1_5</IDENTITE_BOITE_4>
      <IDENTITE_BOITE_5>Boite1_5</IDENTITE_BOITE_5>
   </ROW>
</ROWSET>

这是我的对象模型:

[Serializable]
[System.Xml.Serialization.XmlRoot("DTOFournitureListeImporter")]
public class DTOFournitureListeImporter
{
   [XmlArray("ROWSET")]
   [XmlArrayItem("ROW", typeof(DTOFournitureImporter))]
   public DTOFournitureImporter[] dtoFournitureImporter { get; set; }
}

[Serializable]
public class DTOFournitureImporter
{
   [System.Xml.Serialization.XmlElement("lot")]
   public string lot { get; set; }

   [System.Xml.Serialization.XmlElement("date_trans")]
   public DateTime date_trans { get; set; }

   [System.Xml.Serialization.XmlElement("numero_aa227")]
   public string numero_aa227 { get; set; }

   [System.Xml.Serialization.XmlElement("numero_etui")]
   public string numero_etui { get; set; }

   [System.Xml.Serialization.XmlElement("identite_boite_1")]
   public string identite_boite_1 { get; set; }

   [System.Xml.Serialization.XmlElement("identite_boite_2")]
   public string identite_boite_2 { get; set; }

   [System.Xml.Serialization.XmlElement("identite_boite_3")]
   public string identite_boite_3 { get; set; }

   [System.Xml.Serialization.XmlElement("identite_boite_4")]
   public string identite_boite_4 { get; set; }

   [System.Xml.Serialization.XmlElement("identite_boite_5")]
   public string identite_boite_5 { get; set; }
}

我如何反序列化:

XmlSerializer serializer = new XmlSerializer(typeof(DTOFournitureListeImporter));
TextReader textReader = new StreamReader(model.cheminFichierXML);
DTOFournitureListeImporter dTOFournitureListeImporter = (DTOFournitureListeImporter)serializer.Deserialize(textReader);
textReader.Close();

错误:

  

XML文档中存在错误(2,2)。 -   System.InvalidOperationException:不期望。   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDTOFournitureListeImporter.Read4_DTOFournitureListeImporter()

1 个答案:

答案 0 :(得分:4)

问题可能是XML文件中的所有标记都是大写字母,但是类中的属性表明它们应该是小写字母。

此外,您在属性中说XML根是DTOFournitureListeImporter,但事实并非如此。 XML根目录是ROWSET

总而言之:您尝试创建的结构与XML文件不匹配。