Csharp读写XML

保存
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("Initialize.xml");
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("ComValue").ChildNodes;//获取 节点的所有子节点
            foreach (XmlNode xn in nodeList)//遍历所有子节点
            {
                XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
                if (xe.GetAttribute("name") == "PortName")
                {
                    xe.InnerText = com.PortName.ToString();
                }
                if (xe.GetAttribute("name") == "BaudRate")
                {
                    xe.InnerText = com.BaudRate.ToString();
                }
                if (xe.GetAttribute("name") == "Parity")
                {
                    xe.InnerText = com.Parity.ToString();
                }
                if (xe.GetAttribute("name") == "StopBits")
                {
                    xe.InnerText = com.StopBits.ToString();
                }
            }
            xmlDoc.Save("Initialize.xml");//保存。

读取

 XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("Initialize.xml");
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("ComValue").ChildNodes;//获取 节点的所有子节点
            foreach (XmlNode xn in nodeList)//遍历所有子节点
            {

                XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
                if (xe.GetAttribute("name") == "PortName")
                {
                    com.PortName = xe.InnerText;
                }
                if (xe.GetAttribute("name") == "BaudRate")
                {
                    com.BaudRate = int.Parse(xe.InnerText);
                }
                if (xe.GetAttribute("name") == "Parity")
                {
                    com.Parity = Parity.None;
                }
                if (xe.GetAttribute("name") == "StopBits")
                {
                    com.StopBits = StopBits.One;
                }
            }

 

你可能感兴趣的:(技术文档,代码编程,c#,xml)