Bootstrap

C#中生成和解析Xml,实体与Xml互转等

一:C#中生成和解析Xml

1. 相关说明和解释

命名空间:using System.Xml;
程序集:  System.Xml(在 System.Xml.dll 中)。

涉及到的类和方法:
		XmlDeclaration 类:表示 XML 声明节点:<?xml version='1.0'...?>,XML文件第一行。
		XmlDocument 类:表示 XML 文档。 可使用此类在文档中加载、验证、编辑、添加和放置 XML。
		CreateElement 方法 (String, String, String):创建具有指定 Prefix、LocalName 和 NamespaceURI 的元素。
		Prefix:新元素的前缀(如果有的话)。
		LocalName:新元素的本地名称。
		NamespaceURI:新元素的命名空间 URI(如果有的话)。
		XmlElement 类:表示元素。
		XmlNode 类:表示 XML 文档中的单个节点。
		AppendChild方法:将指定的节点添加到该节点的子节点列表的末尾。
		SelectSingleNode方法:选择第一个 XmlNode ,与 XPath 表达式匹配。

2. 生成Xml

2-1 Xml样例

<?xml version="1.0" encoding="gb2312"?>
<Gen>
  <Zi name="博客园" age="26">
    <title>C#从入门到放弃</title>
    <unit>第一讲,如何放弃</unit>
    <fm>123.06兆赫</fm>
  </Zi>
</Gen>

2-2 C#生成上述2-1的Xml

//创建XmlDocument对象
XmlDocument xmlDoc = new XmlDocument();
//XML的声明<?xml version="1.0" encoding="gb2312"?> 
XmlDeclaration xmlSM = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
 //追加xmldecl位置
xmlDoc.AppendChild(xmlSM);
 //添加一个名为Gen的根节点
XmlElement xml = xmlDoc.CreateElement("", "Gen", "");
//追加Gen的根节点位置
xmlDoc.AppendChild(xml);
//添加另一个节点,与Gen所匹配,查找<Gen>
XmlNode gen = xmlDoc.SelectSingleNode("Gen");
//添加一个名为<Zi>的节点   
XmlElement zi = xmlDoc.CreateElement("Zi");
//为<Zi>节点的属性
zi.SetAttribute("name", "博客园");
zi.SetAttribute("age", "26"); 
XmlElement x1 = xmlDoc.CreateElement("title");
//InnerText:获取或设置节点及其所有子节点的串连值
x1.InnerText = "C#从入门到放弃";
zi.AppendChild(x1);//添加到<Zi>节点中
XmlElement x2 = xmlDoc.CreateElement("unit");
x2.InnerText = "第一讲,如何放弃";
zi.AppendChild(x2);
XmlElement x3 = xmlDoc.CreateElement("fm");
x3.InnerText = "123.06兆赫";
zi.AppendChild(x3);
gen.AppendChild(zi);//添加到<Gen>节点中   
//保存好创建的XML文档
xmlDoc.Save("D:/data.xml");    

3. 解析Xml

3-1 Xml样例

<checkResult>
    <item>
        <fmId>XX0001</fmId>
        <fmItemId>20000RT</fmItemId>
        <checkRuleId>4C6A0458-29B4-4CE6-B38C-38CDEE3CD3C2</checkRuleId>
        <isAcct>不影响</isAcct>
        <soluation>不需要方案,因为不涉及</soluation>
        <evaluate>注意,这是一条评论</evaluate>
    </item>
    <item>
        <fmId>XX0002</fmId>
        <fmItemId>20000RT</fmItemId>
        <checkRuleId>A4C12D83-DC18-427D-839F-7DB68EF730BF</checkRuleId>
        <isAcct>影响</isAcct>
        <soluation>方案还在拟定当中,请注意节奏</soluation>
        <evaluate>It is a evaluate</evaluate>
    </item>
</checkResult>

3-2 C#解析上述3-1的Xml

3-2-1 创建实体类 ==> DizCheckResult
public class DizCheckResult
    {
        public string fmId { get; set; }
        public string fmItemId { get; set; }
        public string checkRuleId { get; set; }
        public string isAcct { get; set; }
        public string soluation { get; set; }
        public string evaluate { get; set; }
    }
3-3-2 解析,将多个item解析后写进实体DizCheckResult,返回集合
public static List<DizCheckResult> GetCheckResultList()
{
    List<DizCheckResult> tmpList = new List<DizCheckResult>();
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(@"f:\myproject\x.xml");
    //XmlNodeList nodelist = xmlDoc.GetElementsByTagName("checkResult/item");
    XmlNodeList nodelist = xmlDoc.SelectNodes("checkResult/item");
    foreach(XmlNode node in nodelist)
    {
        DizCheckResult entity = new DizCheckResult();
        entity.fmId = HttpUtility.HtmlEncode(node["fmId"].InnerText);
        entity.fmItemId = HttpUtility.HtmlEncode(node["fmItemId"].InnerText);
        entity.checkRuleId = node["checkRuleId"].InnerText;
        entity.isAcct = node["isAcct"].InnerText;
        entity.soluation = node["soluation"].InnerText;
        entity.evaluate = node["evaluate"].InnerText;
        tmpList.Add(entity);
    }
    return tmpList;
}

二:C#中实体类与XML相互转换

1. 工具类XmlSerializeHelper

using System;
using System.IO;
using System.Xml.Serialization;
 
/// <summary>
/// XML序列化公共处理类
/// </summary>
public static class XmlSerializeHelper
{
    /// <summary>
    /// 将实体对象转换成XML
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="obj">实体对象</param>
    public static string XmlSerialize<T>(T obj)
    {
        try
        {
            using (StringWriter sw = new StringWriter())
            {
                Type t = obj.GetType();
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(sw, obj);
                sw.Close();
                return sw.ToString();
            }
        }
        catch (Exception ex)
        {
            throw new Exception("将实体对象转换成XML异常", ex);
        }
    }
 
    /// <summary>
    /// 将XML转换成实体对象
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="strXML">XML</param>
    public static T DESerializer<T>(string strXML) where T : class
    {
        try
        {
            using (StringReader sr = new StringReader(strXML))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(sr) as T;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("将XML转换成实体对象异常", ex);
        }
    }
}

2. 创建用户信息类,供后续测试用

/// <summary>
/// 用户信息类
/// </summary>
public class UserInfo
{
    /// <summary>
    /// 编号
    /// </summary>
    public int ID { get; set; }
 
    /// <summary>
    /// 名称
    /// </summary>
    public string Name { get; set; }
 
    /// <summary>
    /// 创建时间
    /// </summary>
    public DateTime? CreateTime { get; set; }
}

3. List与XML互转

/// <summary>
/// List与XML互转
/// </summary>
public static void ListToXmlTest()
{
    //获取用户列表
    List<UserInfo> userList = GetUserList();
 
    //实体转换XML
    string xmlResult = XmlSerializeHelper.XmlSerialize(userList);
 
    //XML转实体
    List<UserInfo> deResult = XmlSerializeHelper.DESerializer<List<UserInfo>>(xmlResult);
}
 
/// <summary>
/// 获取用户信息列表
/// </summary>
public static List<UserInfo> GetUserList()
{
    List<UserInfo> userList = new List<UserInfo>();
    userList.Add(new UserInfo() { ID = 1, Name = "张三", CreateTime = DateTime.Now });
    userList.Add(new UserInfo() { ID = 2, Name = "李四", CreateTime = DateTime.Now });
    userList.Add(new UserInfo() { ID = 2, Name = "王五" });
    return userList;
}

3-1 生成的Xml结果如下:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfUserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <UserInfo>
    <ID>1</ID>
    <Name>张三</Name>
    <CreateTime>2018-10-04T15:59:53.7761027+08:00</CreateTime>
  </UserInfo>
  <UserInfo>
    <ID>2</ID>
    <Name>李四</Name>
    <CreateTime>2018-10-04T15:59:54.9571044+08:00</CreateTime>
  </UserInfo>
  <UserInfo>
    <ID>2</ID>
    <Name>王五</Name>
    <CreateTime xsi:nil="true" />
  </UserInfo>
</ArrayOfUserInfo>

4. DataTable与XML互转

/// <summary>
/// DataTable与XML互转
/// </summary>
public static void DataTableToXmlTest()
{
    //创建DataTable对象
    DataTable dt = CreateDataTable();
 
    //DataTable转XML
    string xmlResult = XmlSerializeHelper.XmlSerialize(dt);
 
    //XML转DataTable
    DataTable deResult = XmlSerializeHelper.DESerializer<DataTable>(xmlResult);
}
 
/// <summary>
/// 创建DataTable对象
/// </summary>
public static DataTable CreateDataTable()
{
    //创建DataTable
    DataTable dt = new DataTable("NewDt");
 
    //创建自增长的ID列
    DataColumn dc = dt.Columns.Add("ID", Type.GetType("System.Int32"));
    dt.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
    dt.Columns.Add(new DataColumn("CreateTime", Type.GetType("System.DateTime")));
 
    //创建数据
    DataRow dr = dt.NewRow();
    dr["ID"] = 1;
    dr["Name"] = "张三";
    dr["CreateTime"] = DateTime.Now;
    dt.Rows.Add(dr);
 
    dr = dt.NewRow();
    dr["ID"] = 2;
    dr["Name"] = "李四";
    dr["CreateTime"] = DateTime.Now;
    dt.Rows.Add(dr);
 
    dr = dt.NewRow();
    dr["ID"] = 3;
    dr["Name"] = "王五";
    dr["CreateTime"] = DateTime.Now;
    dt.Rows.Add(dr);
 
    return dt;
}

4-1 生成的Xml结果如下:

<?xml version="1.0" encoding="utf-16"?>
<DataTable>
  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="NewDt" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="NewDt">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="ID" type="xs:int" minOccurs="0" />
                <xs:element name="Name" type="xs:string" minOccurs="0" />
                <xs:element name="CreateTime" type="xs:dateTime" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <DocumentElement>
      <NewDt diffgr:id="NewDt1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
        <ID>1</ID>
        <Name>张三</Name>
        <CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime>
      </NewDt>
      <NewDt diffgr:id="NewDt2" msdata:rowOrder="1" diffgr:hasChanges="inserted">
        <ID>2</ID>
        <Name>李四</Name>
        <CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime>
      </NewDt>
      <NewDt diffgr:id="NewDt3" msdata:rowOrder="2" diffgr:hasChanges="inserted">
        <ID>3</ID>
        <Name>王五</Name>
        <CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime>
      </NewDt>
    </DocumentElement>
  </diffgr:diffgram>
</DataTable>

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;