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

C# xml移动节点 ...............................................在线等,新手求助
XML code

<?xml version="1.0" encoding="utf-8"?>
<root>
  <left>
<div1>1</div1>
  </left>
  <center>
  </center>
  <right>
  </right>
</root>



C# code

public static void XmlMoveNode(string xmlPath,string oldNode,string newNode,string node)
{
...
}


我想通过 XmlMoveNode("xxx.xml","root/left","root/right","div1");
实现移动节点。得到结果
XML code

<?xml version="1.0" encoding="utf-8"?>
<root>
  <left>
  </left>
  <center>
  </center>
  <right>
<div1>1</div1>
  </right>
</root>


XmlMoveNode方法要怎么实现,求解。最好有代码。谢谢!

------解决方案--------------------
C# code
        //XmlMoveNode("..\\..\\test.xml", "//root/left", "//root/right", "//div1");
        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);
        }