背景
基于xml的数据交换方式已在计算机变成领域中流行多年,虽然现在在互联网领域除了json,但基于xml的配置和数据交换协议还是很常用,今天就总结一个小案例介绍一下在C#中解析xml的实现。
素材
现有xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<TestInfo>
<!-- 测试时间 -->
<TestTime>637043616000000000</TestTime>
<!-- 测试项目 -->
<TestProject>111</TestProject>
<!-- 测试任务 -->
<ScheduleName>222</ScheduleName>
<!-- 电池条码 -->
<BatteryBarCode>333</BatteryBarCode>
<!-- 电池重量 -->
<BatteryWeight>34.845</BatteryWeight>
<!-- 送样人 -->
<Sender>666</Sender>
<!-- 样品编号 -->
<SampleNo>123456</SampleNo>
<!-- 测试人 -->
<TesterName>888</TesterName>
<!-- 用户名 -->
<CurUser>admin</CurUser>
</TestInfo>
程序实现
1、首先编写一个实体类,用于作为xml中数据的载体,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Wongoing.Entity
{
/// <summary>
/// 实验信息
/// </summary>
[Serializable]
public class TestInfo
{
#region 字段定义
private long testTime;
private string testProject;
private string scheduleName;
private string batteryBarCode;
private double batteryWeight;
private string sender;
private string sampleNo;
private string testerName;
private string curUser;
#endregion
#region 属性定义
/// <summary>
/// 测试时间
/// </summary>
public long TestTime
{
get { return testTime; }
set { testTime = value; }
}
/// <summary>
/// 测试项目
/// </summary>
public string TestProject
{
get { return testProject; }
set { testProject = value; }
}
/// <summary>
/// 测试任务
/// </summary>
public string ScheduleName
{
get { return scheduleName; }
set { scheduleName = value; }
}
/// <summary>
/// 电池条码
/// </summary>
public string BatteryBarCode
{
get { return batteryBarCode; }
set { batteryBarCode = value; }
}
/// <summary>
/// 电池重量
/// </summary>
public double BatteryWeight
{
get { return batteryWeight; }
set { batteryWeight = value; }
}
/// <summary>
/// 送样人
/// </summary>
public string Sender
{
get { return sender; }
set { sender = value; }
}
/// <summary>
/// 样品编号
/// </summary>
public string SampleNo
{
get { return sampleNo; }
set { sampleNo = value; }
}
/// <summary>
/// 测试人
/// </summary>
public string TesterName
{
get { return testerName; }
set { testerName = value; }
}
/// <summary>
/// 用户名
/// </summary>
public string CurUser
{
get { return curUser; }
set { curUser = value; }
}
#endregion
}
}
2、编写一个用于解析XML的辅助类,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Wongoing.Entity.Helper
{
/// <summary>
/// 实验信息辅助类
/// </summary>
public class TestInfoHelper
{
/// <summary>
/// 加载测试信息文件
/// </summary>
/// <param name="xmlFile">测试信息文件路径</param>
/// <returns>返回加载好的测试信息对象</returns>
public static TestInfo Load(string xmlFile)
{
TestInfo entity = new TestInfo();
if (System.IO.File.Exists(xmlFile))
{
System.Xml.XmlNode node = null;
string strValue = String.Empty;
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(xmlFile);
#region TestTime - 测试时间
node = doc.SelectSingleNode("./TestInfo/TestTime");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
long testTime = 0;
if (long.TryParse(strValue, out testTime))
{
entity.TestTime = testTime;
}
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取测试时间异常:" + ex.Message);
}
}
#endregion
#region TestProject - 测试项目
node = doc.SelectSingleNode("./TestInfo/TestProject");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
entity.TestProject = strValue;
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取测试项目异常:" + ex.Message);
}
}
#endregion
#region ScheduleName - 测试任务
node = doc.SelectSingleNode("./TestInfo/ScheduleName");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
entity.ScheduleName = strValue;
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取测试任务异常:" + ex.Message);
}
}
#endregion
#region BatteryBarCode - 电池条码
node = doc.SelectSingleNode("./TestInfo/BatteryBarCode");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
entity.BatteryBarCode = strValue;
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取电池条码异常:" + ex.Message);
}
}
#endregion
#region BatteryWeight - 电池重量
node = doc.SelectSingleNode("./TestInfo/BatteryWeight");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
double weight = 0.0;
if (double.TryParse(strValue, out weight))
{
entity.BatteryWeight = weight;
}
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取电池重量异常:" + ex.Message);
}
}
#endregion
#region Sender - 送样人
node = doc.SelectSingleNode("./TestInfo/Sender");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
entity.Sender = strValue;
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取送样人异常:" + ex.Message);
}
}
#endregion
#region SampleNo - 样品编号
node = doc.SelectSingleNode("./TestInfo/SampleNo");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
entity.SampleNo = strValue;
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取样品编号异常:" + ex.Message);
}
}
#endregion
#region TesterName - 测试人
node = doc.SelectSingleNode("./TestInfo/TesterName");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
entity.TesterName = strValue;
}
}
catch(Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取测试人:" + ex.Message);
}
}
#endregion
#region CurUser - 用户名
node = doc.SelectSingleNode("./TestInfo/CurUser");
if (node != null && node.FirstChild != null)
{
try
{
if (GetFirstChildNodeValue(node, true, out strValue))
{
entity.CurUser = strValue;
}
}
catch (Exception ex)
{
Console.WriteLine("Wongoing.Entity.TestInfoHelper.Load获取用户名:" + ex.Message);
}
}
#endregion
}
return entity;
}
/// <summary>
/// 获取当前元素的第一个子节点的值(Text)
/// </summary>
/// <param name="node">当前元素节点</param>
/// <param name="throwException">是否抛出异常</param>
/// <param name="value">输出元素值</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool GetFirstChildNodeValue(System.Xml.XmlNode node, bool throwException, out string value)
{
value = string.Empty;
try
{
value = node.FirstChild.Value.ToString();
}
catch (Exception ex)
{
if (throwException)
{
throw (ex);
}
return false;
}
return true;
}
/// <summary>
/// 获取指定XPath的第一个元素节点的指定属性的值
/// </summary>
/// <param name="node">当前元素节点</param>
/// <param name="path">xpath</param>
/// <param name="attribute">属性</param>
/// <param name="throwException">是否抛出异常</param>
/// <param name="value">输出属性值</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool GetFirstNodeValue(System.Xml.XmlNode node, string path, string attribute, bool throwException, out string value)
{
value = string.Empty;
try
{
value = node.SelectNodes(path)[0].Attributes[attribute.ToLower()].Value.ToString();
}
catch (Exception ex)
{
if (throwException)
{
throw (ex);
}
return false;
}
return true;
}
/// <summary>
/// 获取指定元素的节点的指定属性值
/// </summary>
/// <param name="node">元素节点</param>
/// <param name="attribute">属性</param>
/// <param name="throwException">是否抛出异常</param>
/// <param name="value">输出属性值</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool GetNodeAttributeValue(System.Xml.XmlNode node, string attribute, bool throwException, out string value)
{
value = string.Empty;
try
{
value = node.Attributes[attribute.ToLower()].Value.ToString();
}
catch (Exception ex)
{
if (throwException)
{
throw (ex);
}
return false;
}
return true;
}
/// <summary>
/// 根据索引文件完整路径(不带扩展名)查找实验信息配置文件
/// </summary>
/// <param name="idxFileNameWithoutExt">索引文件完整路径(不带扩展名)</param>
/// <returns>如果找到返回实验信息配置文件完整路径,否则返回String.Empty</returns>
public static string FindTestInfoFile(string idxFileNameWithoutExt)
{
string prefix = "TestInfo_"; //实验信息配置文件前缀
string ext = ".xml"; //实验信息配置文件扩展名
string testInfoFile = String.Empty;
string filePath = System.IO.Path.GetDirectoryName(String.Format("{0}{1}", idxFileNameWithoutExt, ".midx")); //索引数据文件所在的目录
if (System.IO.Directory.Exists(filePath))
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(filePath);
System.IO.FileInfo[] files = di.GetFiles();
foreach (System.IO.FileInfo fi in files)
{
if (fi.Name.Contains(prefix) && fi.Extension.ToLower() == ext)
{
testInfoFile = fi.FullName;
break;
}
}
}
return testInfoFile;
}
}
}
3、编写一段入口代码,调用解析辅助类进行xml文件内容解析,如下:
string testInfoFile = Wongoing.Entity.Helper.TestInfoHelper.FindTestInfoFile(this.txtFilePath.Text); //获取xml文件路径
if (String.IsNullOrEmpty(testInfoFile))
{
MessageBox.Show("没有找到实验信息配置文件!");
return;
}
this.testInfo = Wongoing.Entity.Helper.TestInfoHelper.Load(testInfoFile); //解析为实体
//后面就可以通过this.testInfo的属性使用xml文件中的值了。