<?xml version="1.0" encoding="gb2312"?>
<root>
  <bookstore n="目录">
    <dir id="1" n="gggg">
      <dir id="3"/>
    </dir>
    <dir id="2" n="wwww">
        <dir id="4"/>
    </dir>
  </bookstore>
</root>
求:如何向指定的根节点中插入子节点
如:向id=2的根节点中插入子节点 <dir id="5"/> 或 向id=4的根节点中插入子节点 <dir id="5"/> 
谢谢
   

解决方案 »

  1.   

    XmlNode mynode=myDoc.DocumentElement.SelectSingleNode("//ValidatorGroup[@id='2']");
    至于如何插入之节点,肯定是先创建一个节点,然后添加即可。
     
      

  2.   

    修正
    XmlNode   mynode=myDoc.DocumentElement.SelectSingleNode("//dir[@id='2']"); 
      

  3.   

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Xml;namespace WebApp1.ceshi
    {
        public partial class xml_addnode : System.Web.UI.Page
        {
            XmlDocument xmldoc = new XmlDocument();
            private string fileName = string.Empty;
            protected void Page_Load(object sender, EventArgs e)
            {
                fileName = Server.MapPath("x01.xml");
                xmldoc.Load(fileName);
            }        protected void Button1_Click(object sender, EventArgs e)
            {
                string xpath="/root/bookstore/dir[@id='2']";
                XmlNode xnode = xmldoc.SelectSingleNode(xpath);
                Response.Write(xnode.Attributes["n"].Value);
                XmlNode insert = xmldoc.CreateNode(XmlNodeType.Element,"dir",null);
                XmlAttribute xb = xmldoc.CreateAttribute("id");
                xb.Value = "5";
                insert.Attributes.Append(xb);
                xnode.ParentNode.InsertAfter(insert, xnode);
                xmldoc.Save(fileName);
                Response.Write("添加成功!");
            }
        }
    }