操纵XML文件

我的XML文件是这样的:

<?xml version="1.0" encoding="utf-8"?> <configuration> <root1> <subRoot1>Default</subRoot1> <subRoot2>Default</subRoot2> <subRoot3>Default</subRoot3> </root1> <root2> <subRoot1>Default</subRoot1> </root2> <root3> <subRoot1>Default</subRoot1> <subRoot2>newValue</subRoot2> </root3> </configuration>

 

接下来我们对该XML文件进行操纵

/// <summary> /// XML文件路径 /// </summary> string strXmlFilePath = Directory.GetParent(Directory.GetParent(Application.StartupPath).ToString()) + @"/XMLFile1.xml"; /// <summary> /// 新增节点 /// </summary> private void btnAdd_Click(object sender, EventArgs e) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(strXmlFilePath); XmlNode root = xmlDoc.SelectSingleNode("configuration");//查找根节点 XmlElement xe = xmlDoc.CreateElement("root4");//创建一个<root4>节点 XmlElement xesub1 = xmlDoc.CreateElement("subRoot1"); xesub1.InnerText = "Default";//设置节点文本 xe.AppendChild(xesub1);//添加到<root4>节点中 XmlElement xesub2 = xmlDoc.CreateElement("subRoot2"); xesub2.InnerText = "Default"; xe.AppendChild(xesub2); XmlElement xesub3 = xmlDoc.CreateElement("subRoot3"); xesub3.InnerText = "Default"; xe.AppendChild(xesub3); root.AppendChild(xe);//添加到根节点 xmlDoc.Save(strXmlFilePath);//保存最新XML文件 } /// <summary> /// 删除root4节点 /// </summary> private void btnRemove_Click(object sender, EventArgs e) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(strXmlFilePath); XmlNode root = xmlDoc.DocumentElement; XmlNodeList nodeList = xmlDoc.SelectSingleNode("configuration").ChildNodes;//获取根节点的所有子节点 foreach (XmlNode xn in nodeList) { if (xn.Name == "root4") { //xn.RemoveAll(); //删除该节点下的全部内容 root.RemoveChild(xn); //移除该子节点 break; } } xmlDoc.Save(strXmlFilePath);//保存最新XML文件 } /// <summary> /// 修改root3节点下子节点subRoot2的文本 /// </summary> private void btnUpdate_Click(object sender, EventArgs e) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(strXmlFilePath); XmlNodeList nodeList = xmlDoc.SelectSingleNode("configuration").ChildNodes;//获取根节点的所有子节点 foreach (XmlNode xn in nodeList)//遍历所有子节点 { if (xn.Name == "root3") { XmlNodeList nls = xn.ChildNodes;//继续获取xn子节点的所有子节点 foreach (XmlNode xn1 in nls)//遍历 { if (xn1.Name == "subRoot2")//找到 { xn1.InnerText = "newValue";//修改 break; } } break; } } xmlDoc.Save(strXmlFilePath);//保存最新XML文件 } /// <summary> /// 查看root3节点下子节点subRoot2的文本 /// </summary> private void btnQuery_Click(object sender, EventArgs e) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(strXmlFilePath); XmlNodeList nodeList = xmlDoc.SelectSingleNode("configuration").ChildNodes;//获取根节点的所有子节点 foreach (XmlNode xn in nodeList)//遍历所有子节点 { if (xn.Name == "root3") { XmlNodeList nls = xn.ChildNodes;//继续获取xn子节点的所有子节点 foreach (XmlNode xn1 in nls)//遍历 { if (xn1.Name == "subRoot2")//找到 { label1.Text = xn1.InnerText; break; } } break; } } }

你可能感兴趣的:(xml,object,String,encoding)