Как бы вы написали сериализуемый класс для этого XML-файла? - PullRequest
3 голосов
/ 08 февраля 2011

У меня это XML-файл, и я хотел бы написать сериализуемый класс для использования с XmlSerializer.Deserialize.

Вот файл:

<?xml version="1.0" encoding="UTF-8"?>
<dataroot 
    xmlns:od="urn:schemas-microsoft-com:officedata"     
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      
    xsi:noNamespaceSchemaLocation="AFFEANALLECT.xsd" 
    generated="2011-02-02T13:27:46">
    <AFFEANALLECT>
        <NUMEEMPL>4</NUMEEMPL>
        <TYPETRAV>SOUD</TYPETRAV>
        <CONTRAT>08245</CONTRAT>
        <DATE>2008-03-27 14:09:59</DATE>
        <STATION>02</STATION>
        <HORAIRE>1</HORAIRE>
        <ORIGINE>AFFE FIN</ORIGINE>
    </AFFEANALLECT>
    <AFFEANALLECT>
        <NUMEEMPL>4</NUMEEMPL>
        <TYPETRAV>SOUD</TYPETRAV>
        <CONTRAT>08245</CONTRAT>
        <DATE>2008-03-27 08:29:46</DATE>
        <STATION>02</STATION>
        <HORAIRE>1</HORAIRE>
        <ORIGINE>AFFE DEBUT</ORIGINE>
    </AFFEANALLECT>
</dataroot>

Я сделал что-то вродеэто для одного AFFEANALLECT:

[Serializable()]
public class AFFEANALLECT
{
    public string NUMEEMPL { get; set; }
    public string TYPETRAV { get; set; }
    public string CONTRAT  { get; set; }
    public string DATE     { get; set; }
    public string STATION  { get; set; }
    public string HORAIRE  { get; set; }
    public string ORIGINE  { get; set; }
}

И это прекрасно работает.Теперь единственное, что нужно, это поместить AFFEANALLECT в некоторый хеш-массив с именем "dataroot".

Не могли бы вы указать мне правильное направление, пожалуйста?

Ответы [ 4 ]

6 голосов
/ 08 февраля 2011

Создайте класс как AFFEANALLECTCOLLECTION:

[XmlRoot("dataroot)]
public class AFFEANALLECTCOLLECTION
{
    [XmlElement("AFFEANALLECT")]
    public List<AFFEANALLECT> AFFEANALLECTS {get; set;}

}
5 голосов
/ 08 февраля 2011

Aliostad опубликовал идеальный ответ для конкретного случая; но в общем случае (при наличии xml fragement):

  • сохранить образец где-нибудь как foo.xml
  • в командной строке vs запустите xsd foo.xml (это создает xsd из xml)
  • в командной строке vs запустите xsd foo.xsd /classes (это создает C # из xsd)
  • копия с foo.cs

В этом случае (с использованием всех параметров по умолчанию и т. Д.):

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1.
// 


/// <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)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class dataroot {

    private datarootAFFEANALLECT[] aFFEANALLECTField;

    private string generatedField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("AFFEANALLECT", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public datarootAFFEANALLECT[] AFFEANALLECT {
        get {
            return this.aFFEANALLECTField;
        }
        set {
            this.aFFEANALLECTField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string generated {
        get {
            return this.generatedField;
        }
        set {
            this.generatedField = value;
        }
    }
}

/// <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)]
public partial class datarootAFFEANALLECT {

    private string nUMEEMPLField;

    private string tYPETRAVField;

    private string cONTRATField;

    private string dATEField;

    private string sTATIONField;

    private string hORAIREField;

    private string oRIGINEField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string NUMEEMPL {
        get {
            return this.nUMEEMPLField;
        }
        set {
            this.nUMEEMPLField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string TYPETRAV {
        get {
            return this.tYPETRAVField;
        }
        set {
            this.tYPETRAVField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string CONTRAT {
        get {
            return this.cONTRATField;
        }
        set {
            this.cONTRATField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string DATE {
        get {
            return this.dATEField;
        }
        set {
            this.dATEField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string STATION {
        get {
            return this.sTATIONField;
        }
        set {
            this.sTATIONField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string HORAIRE {
        get {
            return this.hORAIREField;
        }
        set {
            this.hORAIREField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string ORIGINE {
        get {
            return this.oRIGINEField;
        }
        set {
            this.oRIGINEField = value;
        }
    }
}

/// <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)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSet {

    private dataroot[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("dataroot")]
    public dataroot[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}
2 голосов
/ 08 февраля 2011

Посмотрите на атрибут XMLSerializable и его параметры, вы можете точно контролировать полученное пространство имен и свойства документа xml.

1 голос
/ 08 февраля 2011

Если я не ошибаюсь, если вы используете List<AFFEANALLECT> и сериализуете этот список, вы сможете получить нужный вам формат

...