使用序列化将 XML 数据转换为对象,反之亦然






2.80/5 (23投票s)
2005年5月18日

210996
本文档描述了将 XSD 转换为类,然后将 XML 读取和写入类对象的过程。
引言
将 XML 保存到类对象可以提供更大的灵活性和可维护性。此外,与使用 DataSet
相比,这是从 Web 服务返回数据的首选方式。将 XML 保存到类对象称为序列化,而使用反向过程读取则称为反序列化。
流程/示例
让我们以一个名为 Emp.XSD 的 XSD 为例
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="Emp">
<xs:complexType>
<xs:sequence>
<xs:element name="EmpInfo" type="EmpInfo"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="EmpInfo">
<xs:sequence>
<xs:element name="Code" type="requiredString"/>
<xs:element name="FirstName" type="requiredString"/>
<xs:element name="LastName" type="requiredString"/>
<xs:element name="Destination" type="requiredString"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="requiredString">
<xs:annotation>
<xs:documentation>template for required strings</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="optionalString">
<xs:annotation>
<xs:documentation>template for optional strings</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:minLength value="0"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
现在,要从 XSD 转换类,我们将运行以下命令
xsd C:\Emp.xsd /t:lib /l:cs /c
从 Visual Studio .NET 2003 命令提示符。这将创建一个名为 Emp
的类文件。
EMP 类
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.2032
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by xsd, Version=1.1.4322.2032.
//
using System.Xml.Serialization;
/// <remarks/>
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class Emp {
/// <remarks/>
public EmpInfo EmpInfo;
}
/// <remarks/>
public class EmpInfo {
/// <remarks/>
public string Code;
/// <remarks/>
public string FirstName;
/// <remarks/>
public string LastName;
/// <remarks/>
public string Destination;
}
现在,我们可以使用以下函数将员工 XML 数据保存到该类
/// <summary>
/// Returns an emp xsd class object based on the xml data passed
/// </summary>
/// <param name="xml">xml data of employee</param>
/// <returns></returns>
public Emp EmpObject(string xml)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
// serialise to object
XmlSerializer serializer = new XmlSerializer(typeof(Emp));
stream = new StringReader(xml); // read xml data
reader = new XmlTextReader(stream); // create reader
// covert reader to object
return (Emp)serializer.Deserialize(reader);
}
catch
{
return null;
}
finally
{
if(stream != null) stream.Close();
if(reader != null) reader.Close();
}
}
要根据 Emp
类对象获取 XML,请使用以下函数
/// <summary>
/// Returns the xml as string based on emp object values
/// </summary>
/// <param name="emp">object that would be converted into xml</param>
/// <returns></returns>
public string EmpXml(Emp emp)
{
MemoryStream stream = null;
TextWriter writer = null;
try
{
stream = new MemoryStream(); // read xml in memory
writer = new StreamWriter(stream, Encoding.Unicode) ;
// get serialise object
XmlSerializer serializer = new XmlSerializer(typeof(Emp));
serializer.Serialize(writer, emp); // read object
int count = (int) stream.Length; // saves object in memory stream
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
// copy stream contents in byte array
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding(); // convert byte array to string
return utf.GetString(arr).Trim();
}
catch
{
return string.Empty;
}
finally
{
if(stream != null) stream.Close();
if(writer != null) writer.Close();
}
}