philzhou

导航

map xml to entity

在使用xml作为系统配置时,免不了需要将xml文件读取出来,并转换成相应的实体。但是,如果需要自己去操作xml文件的每一个节点,将其组装成实体,这个工作确实相当繁琐的,所以一般我们会写一个实体,然后使用下面的这种方式来反序列化。

[XmlRoot("PersonInfoXml")]
public class Person
{
    [XmlElement("Name")]
    public Identifier PersonIdentify
    {
        get
        {
            if (mIdentify == null) mIdentify = new Identifier();
            return mIdentify;
        }
        set { mIdentify = value; }
    }
    [XmlElement("Address")]
    public Address PersonAddress
    {
        get
        {
            if (mAddress == null)
                mAddress = new Address();
            return mAddress;
        }
        set { mAddress = value; }
    }
    [XmlElement("Education")]
    public Education PersonEducation
    {
        get
        {
            if (mEducation == null)
                mEducation = new Education();
            return mEducation;
        }
        set { mEducation = value; }
    }

这种方式还是需要编写相应的实体类,也比较麻烦。

最简单的方式是为xml编写xml schema文件定义即xsd(xml sechema definition)

然后使用xsd工具生成相应的实体类,再反序列化就可以了,xsd文件不仅可以用来生成实体,还可以用来检查xml文件的语法,对xml提供智能提示。

 

已下为一个简单的范例:

note.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
  <xs:element name="note">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="to" type="xs:string"/>
        <xs:element name="from" type="xs:string"/>
        <xs:element name="heading" type="xs:string"/>
        <xs:element name="body" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

 

note.xml

<?xml version="1.0" encoding="UTF-8"?>
<note xmlns="http://www.w3schools.com">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>it's a note</body>
</note>

 

xsd.exe工具生成的note.cs

打开VS提示命令

xsd filename /classes

//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.269
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

/// <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 = "http://www.w3schools.com")]
[System.Xml.Serialization.XmlRootAttribute("note", Namespace = "http://www.w3schools.com", IsNullable = false)]
public partial class note {
   
    private string toField;
   
    private string fromField;
   
    private string headingField;
   
    private string bodyField;
   
    /// <remarks/>
    public string to {
        get {
            return this.toField;
        }
        set {
            this.toField = value;
        }
    }
   
    /// <remarks/>
    public string from {
        get {
            return this.fromField;
        }
        set {
            this.fromField = value;
        }
    }
   
    /// <remarks/>
    public string heading {
        get {
            return this.headingField;
        }
        set {
            this.headingField = value;
        }
    }
   
    /// <remarks/>
    public string body {
        get {
            return this.bodyField;
        }
        set {
            this.bodyField = value;
        }
    }
}

 

code snippet to deserialize xml:

            var path = @"D:\note.xml";
            var serializer = new XmlSerializer(typeof (note));
            var stream = new StreamReader(path);
            var reader = new StringReader(stream.ReadToEnd());
            var n = (note)serializer.Deserialize(reader);
            Assert.AreEqual("Jani", n.from);

posted on 2012-11-18 22:36  philzhou  阅读(1298)  评论(2编辑  收藏  举报