C# 利用xml文件写配置文件

先在配置文件里写好需要的配置内容

<?xml version="1.0" encoding="utf-8"?>
<Configure>
  <portConfigure>
    <PortName>COM4</PortName>
    <BaudRate>90</BaudRate>
    <DataBits>8</DataBits>
    <StopBits>1</StopBits>
    <Parity>None</Parity>
  </portConfigure>
  <plcConfigure>
    <plcIP>192.168.0.1</plcIP>
  </plcConfigure>
</Configure>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "example.xml";
            XmlDocument xml = new XmlDocument();
            //打开一个xml
            try
            {
                xml.Load(path);
                //获取portConfigure配置节点
                XmlNode  portConfigure = xml.SelectSingleNode("Configure/portConfigure");
                //读取节点数据
                string portName = portConfigure.SelectSingleNode("PortName").InnerText;
                Console.WriteLine(portName);
                //写入节点数据
                portConfigure.SelectSingleNode("BaudRate").InnerText = "90";
                string BaudRate = portConfigure.SelectSingleNode("BaudRate").InnerText;
                Console.WriteLine(BaudRate);
                xml.Save(path);
                //获取plcConfigure配置节点
                XmlNode PlcConfigure=xml .SelectSingleNode ("Configure/plcConfigure");
                Console.WriteLine(PlcConfigure.SelectSingleNode("plcIP").InnerText );
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message );
            }
        }
    }
}




猜你喜欢

转载自blog.csdn.net/yue1453544229/article/details/80515775