日期:2014-05-17  浏览次数:21063 次

C# 操作xml移动节点到指定位置.............................................新手求解,在线等
XML code

<?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>



C# code

/// <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);
        }



XmlMoveNode(xxx.xml,"root/left","root/right","div1");
这个方法只实现了将div1子节点从left移动到right,放在right最后一位。
我想修改XmlMoveNode(xxx.xml,"root/left","root/right","div1",2);
实现将div1子节点从left移动到right的第二个
结果如下:
XML code

<?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()的源码。先谢过了。

------解决方案--------------------
C# code

        //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);
            }
            //