C# XML文件创建保存、子节点及属性操作

C# XML文件创建保存、子节点及属性操作

        /// <summary>
        /// 创建添加并保存XML文件
        /// </summary>
        private void CreatAndSaveXML()
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8",null);

            xmlDoc.AppendChild(xmlDec);
            //添加根节点
            XmlElement nodeRoot = xmlDoc.CreateElement("Templete");
            xmlDoc.AppendChild(nodeRoot);
            //添加新节点
            XmlElement nodeTemp1 = xmlDoc.CreateElement("nodeTemp");
            //添加节点数据
            nodeTemp1.InnerText = "测试节点1";
            //添加节点属性
            nodeTemp1.SetAttribute("Attribute1", "123");
            nodeTemp1.SetAttribute("Attribute2", "456");
            nodeTemp1.SetAttribute("Attribute3", "789");
            nodeRoot.AppendChild(nodeTemp1);
            //添加新节点
            XmlElement nodeTemp2 = nodeTemp1.Clone() as XmlElement;
            nodeTemp1.InnerText = "测试节点2";
            nodeTemp2.SetAttribute("Attribute1", "123");
            nodeTemp2.SetAttribute("Attribute2", "456");
            nodeTemp2.SetAttribute("Attribute3", "789");
            nodeRoot.AppendChild(nodeTemp2);

            xmlDoc.Save(Application.StartupPath + "\\xmlTemp.xml");
        }

/// <summary> /// 加载遍历XML文件 /// </summary> private void LoadAndTraversal() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Application .StartupPath+ "\\xmlTemp.xml"); //读取根节点 XmlElement nodeElement = xmlDoc.SelectSingleNode("Templete") as XmlElement; if (nodeElement != null) { XmlNodeList nodeList = nodeElement.ChildNodes; //子节点遍历 if (nodeList != null && nodeList.Count > 0) { foreach (XmlNode nodeItem in nodeList) { //获取子节点属性 string att1 = (nodeItem as XmlElement).GetAttribute("Attribute1"); Console.WriteLine(att1); } } } }

 

C# XML文件创建保存、子节点及属性操作

上一篇:大数据学习路线图


下一篇:把dataGridView数据保存到已有的Excel表中