文章目录
- 第一部分:C#中生成和解析Xml
-
- 1. 相关说明和解释
- 2. 生成Xml
-
- 2-1 Xml样例
- 2-2 C#生成上述2-1的Xml
- 3. 解析Xml
-
- 3-1 Xml样例
- 3-2 C#解析上述3-1的Xml
-
- 3-2-1 创建实体类 ==> DizCheckResult
- 3-3-3 解析
- 第二部分:C#中实体类与XML相互转换
-
- 1. 工具类XmlSerializeHelper
- 2. 创建用户信息类,供后续测试用
- 3. List与XML互转
-
- 4. DataTable与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样例
<Gen>
<Zi name="博客园" age="26">
<title>C#从入门到放弃title>
<unit>第一讲,如何放弃unit>
<fm>123.06兆赫fm>
Zi>
Gen>
2-2 C#生成上述2-1的Xml
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlSM = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xmlDoc.AppendChild(xmlSM);
XmlElement xml = xmlDoc.CreateElement("", "Gen", "");
xmlDoc.AppendChild(xml);
XmlNode gen = xmlDoc.SelectSingleNode("Gen");
XmlElement zi = xmlDoc.CreateElement("Zi");
zi.SetAttribute("name", "博客园");
zi.SetAttribute("age", "26");
XmlElement x1 = xmlDoc.CreateElement("title");
x1.InnerText = "C#从入门到放弃";
zi.AppendChild(x1);
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);
xmlDoc.Save("D:/data.xml");
3. 解析Xml
3-1 Xml样例
<checkResult>
<item>
<fmId>XX0001fmId>
<fmItemId>20000RTfmItemId>
<checkRuleId>4C6A0458-29B4-4CE6-B38C-38CDEE3CD3C2checkRuleId>
<isAcct>不影响isAcct>
<soluation>不需要方案,因为不涉及soluation>
<evaluate>注意,这是一条评论evaluate>
item>
<item>
<fmId>XX0002fmId>
<fmItemId>20000RTfmItemId>
<checkRuleId>A4C12D83-DC18-427D-839F-7DB68EF730BFcheckRuleId>
<isAcct>影响isAcct>
<soluation>方案还在拟定当中,请注意节奏soluation>
<evaluate>It is a evaluateevaluate>
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-3 解析
public static List<DizCheckResult> GetCheckResultList()
{
List<DizCheckResult> tmpList = new List<DizCheckResult>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"f:\myproject\x.xml");
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;
public static class XmlSerializeHelper
{
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);
}
}
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. 创建用户信息类,供后续测试用
public class UserInfo
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime? CreateTime { get; set; }
}
3. List与XML互转
public static void ListToXmlTest()
{
List<UserInfo> userList = GetUserList();
string xmlResult = XmlSerializeHelper.XmlSerialize(userList);
List<UserInfo> deResult = XmlSerializeHelper.DESerializer<List<UserInfo>>(xmlResult);
}
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结果如下:
<ArrayOfUserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UserInfo>
<ID>1ID>
<Name>张三Name>
<CreateTime>2018-10-04T15:59:53.7761027+08:00CreateTime>
UserInfo>
<UserInfo>
<ID>2ID>
<Name>李四Name>
<CreateTime>2018-10-04T15:59:54.9571044+08:00CreateTime>
UserInfo>
<UserInfo>
<ID>2ID>
<Name>王五Name>
<CreateTime xsi:nil="true" />
UserInfo>
ArrayOfUserInfo>
4. DataTable与XML互转
public static void DataTableToXmlTest()
{
DataTable dt = CreateDataTable();
string xmlResult = XmlSerializeHelper.XmlSerialize(dt);
DataTable deResult = XmlSerializeHelper.DESerializer<DataTable>(xmlResult);
}
public static DataTable CreateDataTable()
{
DataTable dt = new DataTable("NewDt");
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结果如下:
<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>1ID>
<Name>张三Name>
<CreateTime>2018-10-04T16:06:10.8004082+08:00CreateTime>
NewDt>
<NewDt diffgr:id="NewDt2" msdata:rowOrder="1" diffgr:hasChanges="inserted">
<ID>2ID>
<Name>李四Name>
<CreateTime>2018-10-04T16:06:10.8004082+08:00CreateTime>
NewDt>
<NewDt diffgr:id="NewDt3" msdata:rowOrder="2" diffgr:hasChanges="inserted">
<ID>3ID>
<Name>王五Name>
<CreateTime>2018-10-04T16:06:10.8004082+08:00CreateTime>
NewDt>
DocumentElement>
diffgr:diffgram>
DataTable>