C# 操作xml移动节点到指定位置.............................................新手求解,在线等
<?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); } //获取需要移动到的目标节点 XmlNode yNode = xDoc.SelectSingleNode(newNode); //判断目标节点是否有足够的子节点,有则按顺序插入,没有则添加。 if (yNode.HasChildNodes && yNode.ChildNodes.Count > index - 1) { //在目标节点指定的位置插入要移动的节点 yNode.InsertAfter(targetNode, yNode.ChildNodes[index - 2]); } else { yNode.AppendChild(targetNode); } xDoc.Save(xmlPath); }