日期:2014-05-17 浏览次数:21063 次
<?xml version="1.0" encoding="utf-8"?> <root> <left> <div1></div1> <div2></div2> <div3></div3> </left> <center> <div4></div4> <div5></div5> <div6></div6> </center> <right> <div7></div7> <div8></div8> <div9></div9> </right> </root>
/// <summary> /// 将节点下的子节点移动至其他节点下 /// <root> /// <test> /// <test2></test2> /// </test> /// <test1> /// </test1> /// </root> /// 将test2移动到test1下 /// </summary> /// <param name="xmlPath">xxx.xml</param> /// <param name="oldNode">root/test</param> /// <param name="newNode">root/test1</param> /// <param name="node">test2</param> public static void XmlMoveNode(string xmlPath, string oldNode, string newNode, string node) { XmlDocument xDoc = new XmlDocument(); //加载app.config xDoc.Load(xmlPath); XmlNode xNode = xDoc.SelectSingleNode(oldNode); XmlNode targetNode = xNode.SelectSingleNode(node); ; if (targetNode == null) { throw new Exception("Node not found:" + node); } else { xNode.RemoveChild(targetNode); } XmlNode yNode = xDoc.SelectSingleNode(newNode); yNode.AppendChild(targetNode); xDoc.Save(xmlPath); }
<?xml version="1.0" encoding="utf-8"?> <root> <left> <div2></div2> <div3></div3> </left> <center> <div4></div4> <div5></div5> <div6></div6> </center> <right> <div7></div7> <div1></div1> <div8></div8> <div9></div9> </right> </root>
//XmlMoveNode("..\\..\\test.xml", "//root/left", "//root/right", "//div1",2); public static void XmlMoveNode(string xmlPath, string oldNode, string newNode, string node, int index) { XmlDocument xDoc = new XmlDocument(); //加载xml文件 xDoc.Load(xmlPath); //获取原来所在节点 XmlNode xNode = xDoc.SelectSingleNode(oldNode); //获取要移动的节点 XmlNode targetNode = xNode.SelectSingleNode(node); ; if (targetNode == null) { throw new Exception("Node not found:" + node); } else { //在原位置删掉要移动的节点 xNode.RemoveChild(targetNode); } //