C#讀取Xml檔案

Tiger_shl發表於2018-11-26

 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;
            }
        }

 

相關文章