2010-11-03 9 views
8

Avendo problemi di deserializzazione di alcuni xml in un oggetto in C#.C# Deserialize XML all'oggetto

L'errore che ricevo è ...

xmlns=''> was not expected. 

Il XSD che ho ricevuto per generare la mia classe è la seguente ...

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema targetNamespace="xml.AAAAAAA.com/commerce/apres-vente_technique/assistance" xmlns:pgp="xml.AAAAAAA.com/commerce/apres-vente_technique/assistance" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> 
    <xs:element name="ListeAvisRemboursements"> 
     <xs:annotation> 
      <xs:documentation>Liste des avis de remboursements</xs:documentation> 
     </xs:annotation> 
     <xs:complexType> 
      <xs:sequence maxOccurs="unbounded"> 
       <xs:element name="AvisRemboursement" type="pgp:AvisRemboursementType"/> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
    <xs:complexType name="AvisRemboursementType"> 
     <xs:annotation> 
      <xs:documentation>Avis de remboursement lié à une DC</xs:documentation> 
     </xs:annotation> 
     <xs:sequence> 

(snipped)

Il il file che sto tentando di importare è il seguente:

<?xml version="1.0" encoding="UTF-8"?> 
<ListeAvisRemboursements xmlns:ast="xml.AAAAAAA.com/commerce/apres-vente_technique/assistance"> 
    <ast:AvisRemboursement NumeroDT="3826961" CodeRA="020545G01" NumeroDC="1"> 
     <ast:DateTraitement>2010-06-22</ast:DateTraitement> 
     <ast:MontantDC>25.0</ast:MontantDC> 
     <ast:MontantMO>0.0</ast:MontantMO> 
     <ast:SommeAD>25.0</ast:SommeAD> 
     <ast:MontantPR>0.0</ast:MontantPR> 
     <ast:SommePR>0.0</ast:SommePR> 
     <ast:FraisGestion>0.0</ast:FraisGestion> 
     <ast:NombreHeuresTotalRemboursees>0</ast:NombreHeuresTotalRemboursees> 
     <ast:Etat>C</ast:Etat> 
     <ast:NoteCredit>319984</ast:NoteCredit> 
     <ast:Imputation>030</ast:Imputation> 
     <ast:ListInterventionsPR/> 
     <ast:ListInterventionsMO/> 
    </ast:AvisRemboursement> 

(snipped)

Io penso ciò che sta accadendo è che quando tenta di Net derserialize il xml, colpisce la prima linea che contiene le "xmlns: ast" e lamentele su di esso. Da quanto ho capito, .Net cercherà di mappare gli attributi a una proprietà pubblica della classe di destinazione (e non ci vorrà trovare uno chiamato xmlns. O c'è qualcosa che non va come sto maneggiando gli spazi dei nomi.

Il mio codice di deserializzazione si presenta come segue:

XmlDocument _Doc = new XmlDocument(); 
    _Doc.Load(@"C:\inputfile.xml"); 

    XmlSerializer _XMLSer = new XmlSerializer(typeof(ListeAvisRemboursements)); 
    ListeAvisRemboursements _X = (ListeAvisRemboursements)_XMLSer.Deserialize(new StringReader(_Doc.OuterXml)); 

ho anche provato diverse combinazioni di aggiunta di un manager namespace al documento XML ..

XmlNamespaceManager _Ns = new XmlNamespaceManager(_Doc.NameTable); 
_Ns.AddNamespace("ast", "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance"); 

capisco che ci sia un senso che posso usare questo per dire che cosa .Net namespace da accettare.

Sarebbe utile per qualche aiuto con questo problema.

--- Updated at richiesta con classe di frammento (scusate già compreso prima) questo è stato creato con xsd.exe ---

/// <remarks/> 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] 
    [System.SerializableAttribute()] 
    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance")] 
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance", IsNullable = false)] 
    public partial class ListeAvisRemboursements 
    { 

     private AvisRemboursementType[] avisRemboursementField; 

     /// <remarks/> 
     [System.Xml.Serialization.XmlElementAttribute("AvisRemboursement")] 
     public AvisRemboursementType[] AvisRemboursement 
     { 
      get 
      { 
       return this.avisRemboursementField; 
      } 
      set 
      { 
       this.avisRemboursementField = value; 
      } 
     } 
    } 

    /// <remarks/> 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] 
    [System.SerializableAttribute()] 
    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance")] 
    public partial class AvisRemboursementType 
    { 

     private System.DateTime dateTraitementField; 

     private double montantDCField; 

     private double montantMOField; 

     private double sommeADField; 

     private double montantPRField; 
+1

potresti inserire il frammento della tua lezione ListeAvisRourses ... – RameshVel

risposta

19

Senza una completa xsd/xml, o (in alternativa) il vostro C# classi, non possiamo riprodurre. Ma lavorando dal xml in su, questo funziona bene per me; significato: l'errore non è (per quanto posso vedere) nel codice/dati che hai postato. Puoi pubblicare un esempio più completo (riproducibile)?

public class ListeAvisRemboursements 
{ 
    private readonly List<AvisRemboursement> items = new List<AvisRemboursement>(); 
    [XmlElement("AvisRemboursement", Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance")] 
    public List<AvisRemboursement> Items { get { return items; } } 
} 
public class AvisRemboursement 
{ 
    [XmlAttribute] public string NumeroDT {get;set;} 
    [XmlAttribute] public string CodeRA {get;set;} 
    [XmlAttribute] public string NumeroDC {get;set;} 
    public DateTime DateTraitement { get; set; } 
    public decimal MontantDC { get; set; } 
    public decimal MontantMO { get; set; } 
    public decimal SommeAD { get; set; } 
    public decimal MontantPR { get; set; } 
    public decimal SommePR { get; set; } 
    public decimal FraisGestion { get; set; } 
    public int NombreHeuresTotalRemboursees { get; set; } 
    public string Etat { get; set; } 
    public string NoteCredit { get; set; } 
    public string Imputation { get; set; } 
} 
static void Main() 
{ 
    var ser = new XmlSerializer(typeof(ListeAvisRemboursements)); 
    var wrapper = (ListeAvisRemboursements)ser.Deserialize(new StringReader(xml)); 
    // inspect wrapper.Items etc 
} 

funziona anche bene con:

var ser = new XmlSerializer(typeof(ListeAvisRemboursements)); 
using (var reader = XmlReader.Create("inputfile.xml")) 
{ 
    var wrapper = (ListeAvisRemboursements)ser.Deserialize(reader); 
} 

e:

XmlDocument _Doc = new XmlDocument(); 
_Doc.Load("inputfile.xml"); 
var ser = new XmlSerializer(typeof(ListeAvisRemboursements)); 
var wrapper = (ListeAvisRemboursements)ser.Deserialize(new StringReader(_Doc.OuterXml)); 

e

XmlDocument _Doc = new XmlDocument(); 
_Doc.Load("inputfile.xml"); 
var ser = new XmlSerializer(typeof(ListeAvisRemboursements)); 
var wrapper = (ListeAvisRemboursements)ser.Deserialize(new XmlNodeReader(_Doc.DocumentElement)); 
+0

Il problema è stato rintracciato nelle definizioni di spazio dei nomi errate nel file di input. – Remotec

0

Ecco quello che sto usando (scusate sono un po 'tardi alla festa):

Public Function Serialize(Of YourXMLClass)(ByVal obj As YourXMLClass, 
                 Optional ByVal omitXMLDeclaration As Boolean = True, 
                 Optional ByVal omitXMLNamespace As Boolean = True) As String 

     Dim serializer As New XmlSerializer(obj.GetType) 
     Using memStream As New MemoryStream() 
      Dim settings As New XmlWriterSettings() With { 
        .Encoding = Encoding.UTF8, 
        .Indent = True, 
        .OmitXmlDeclaration = omitXMLDeclaration} 

      Using writer As XmlWriter = XmlWriter.Create(memStream, settings) 
       Dim xns As New XmlSerializerNamespaces 
       If (omitXMLNamespace) Then xns.Add("", "") 
       serializer.Serialize(writer, obj, xns) 
      End Using 

      Return Encoding.UTF8.GetString(memStream.ToArray()) 
     End Using 
    End Function 

Public Function Deserialize(Of YourXMLClass)(ByVal obj As YourXMLClass, ByVal xml As String) As YourXMLClass 
     Dim result As YourXMLClass 
     Dim serializer As New XmlSerializer(GetType(YourXMLClass)) 

     Using memStream As New MemoryStream() 
      Dim bytes As Byte() = Encoding.UTF8.GetBytes(xml.ToArray) 
      memStream.Write(bytes, 0, bytes.Count) 
      memStream.Seek(0, SeekOrigin.Begin) 

      Using reader As XmlReader = XmlReader.Create(memStream) 
       result = DirectCast(serializer.Deserialize(reader), YourXMLClass) 
      End Using 

     End Using 
     Return result 
    End Function