用XSD自动生成XML对应的.NET实体类

在做测试的过程中,测试数据会保存到一个XML文件里面,很多时候还是先有测试数据(XML),后面才会去做测试。在C#里面,读取XML的方法有很多,最近用了一下XmlSerializer,感觉非常爽!

自己先编一个XML文件,也就是测试数据:


    Magus
    open5555

      29
      30

      77
      21


然后利用XSD.EXE工具自动生成一个相应的实例类,不用自己编了~,输入命令

xsd XMLFile1.xml

这样会默认生成一个XMLFile1.xsd文件,然后再根据这个xsd文件来生成相应的C#实例类

xsd XMLFile1.xsd /c

默认会生成一个XMLFile1.cs的实例类

using System.Xml.Serialization;

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRoot()]
public partial class Config {

    private string userNameField;

    private string passwordField;

    private ConfigData[] dataField;

    ///
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string UserName {
        get {
            return this.userNameField;
        }
        set {
            this.userNameField = value;
        }
    }

    ///
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Password {
        get {
            return this.passwordField;
        }
        set {
            this.passwordField = value;
        }
    }

    ///
    [System.Xml.Serialization.XmlElementAttribute("Data", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public ConfigData[] Data {
        get {
            return this.dataField;
        }
        set {
            this.dataField = value;
        }
    }
}

///
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class ConfigData {

    private string manField;

    private string ladyField;

    ///
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Man {
        get {
            return this.manField;
        }
        set {
            this.manField = value;
        }
    }

    ///
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Lady {
        get {
            return this.ladyField;
        }
        set {
            this.ladyField = value;
        }
    }
}

///
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSet {

    private Config[] itemsField;

    ///
    [System.Xml.Serialization.XmlElementAttribute("Config")]
    public Config[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

然后把XMLFile1.cs和XMLFile1.xml拷到项目底下就可以用了~非常方便~

用的时候:

XmlSerializer xs = new XmlSerializer(typeof(Config));
FileStream fs = new FileStream("XMLFile1.xml", FileMode.Open);
Config config = (Config)xs.Deserialize(fs);
String name = config.UserName

Leave a Reply

Your email address will not be published. Required fields are marked *