一
xml结构如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<file>C:\Users\Desktop\机台数据\eventdata.txt</file>
<line>SA5R22EB-27B4-48D7-9DE9-C9DF6DDF61AF</line><!--1406-->
<MachinePlatNO>1</MachinePlatNO>
</connectionStrings>
<connectionStrings>
<file>C:\Users\Desktop\机台数据\eventdata.txt</file>
<line>URH672EB-27B4-48D7-9DE9-C9DF6DDF61AF</line>
<!--1406-->
<MachinePlatNO>1</MachinePlatNO>
</connectionStrings>
<connectionStrings>
<file>C:\Users\Desktop\机台数据\eventdata.txt</file>
<line>ADF672EB-27B4-48D7-9DE9-C9DF6DDF61AF</line>
<!--1406-->
<MachinePlatNO>1</MachinePlatNO>
</connectionStrings>
</configuration>
解析方法如下:
private List<MachInfo> ReadXMLInfo()
{
try
{
List<MachInfo> machInfos = new List<MachInfo>();
XmlDocument xmlDoc = new XmlDocument();
//读取XML文件
xmlDoc.Load(@"D:\SMT生产看板桌面端服务端\SMTWindowsService\WindowsService\DataHandle\LocalXML.xml");
//遍历读取根节点下所有子节点
XmlElement xmlElement = xmlDoc.DocumentElement;//取到根结点
foreach (XmlNode xmlNode in xmlElement.ChildNodes)
{
MachInfo machInfo = new MachInfo();
//文件路径
machInfo.file = xmlNode.SelectSingleNode("file").InnerText;
//线体
machInfo.line = xmlNode.SelectSingleNode("line").InnerText;
//机台号
machInfo.MachinePlatNO = xmlNode.SelectSingleNode("MachinePlatNO").InnerText;
machInfos.Add(machInfo);
}
//读取指定节点
//XmlNode xmlNode = xmlDoc.SelectSingleNode("//connectionStrings");
////文件路径
//file = xmlNode.SelectSingleNode("file").InnerText;
////线体
//line = xmlNode.SelectSingleNode("line").InnerText;
////机台号
//MachinePlatNO = xmlNode.SelectSingleNode("MachinePlatNO").InnerText;
return machInfos;
}
catch (Exception e)
{
return null;
}
}
二.
/// <summary>
/// 获取路径配置
/// </summary>
/// <returns></returns>
public string GetSMTPath()
{
string path = string.Empty;
try
{
path = GetXmlNodeValue("Config/SMTPath/Path");
}
catch
{
path = "";
}
return path;
}
/// <summary>
/// 读取指定节点的值(InnerText)
/// </summary>
/// <param name="strNode">节点名称</param>
/// <returns></returns>
private string GetXmlNodeValue(string strNode)
{
//if (!File.Exists(path))
//{
// var file=File.Create(path);
// file.Close();
//}
xmlDoc.Load(path);
string strReturn = String.Empty;
try
{
//根据路径获取节点
XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode);
if (!(xmlNode == null))
strReturn = xmlNode.InnerText;
}
catch (XmlException xmle)
{
throw xmle;
}
return strReturn;
}
//XML文件格式格式
<?xml version="1.0" encoding="UTF-8"?>
<Config>
<LoginUser>
<UserCode>04558</UserCode>
<Name>张三</Name>
<LoginTime>2019/12/20 11:40:54</LoginTime>
</LoginUser>
<SMTPath>
<Path>C:\Users\Desktop\Test1.log</Path>
</SMTPath>
</Config>