xml追加节点

添加方法

public void XmlAppend(VisitM vm)
{
XmlDocument xmldoc = new XmlDocument();
string path = Server.MapPath("~/Content/VisitFile/VisitFile.xml");
xmldoc.Load(path);

XmlElement node = xmldoc.CreateElement("VisitRecord");
node.SetAttribute("Ip", vm.Ip);
node.SetAttribute("VisitTime", vm.VisitTime);
node.SetAttribute("Word", vm.Word);
//node.SetAttribute("isMobile", vm.isMobile);
node.InnerText=vm.Word;

//将节点加入到指定的节点下
XmlNode xml = xmldoc.DocumentElement.PrependChild(node);
xmldoc.Save(path);
}

  protected void Button3_Click(object sender, EventArgs e)
    {

        //加载xml文档
        XmlDocument doc = new XmlDocument();
        string path = Server.MapPath("~/Title.xml");
        doc.Load(path);
        //创建节点
        XmlElement xmlElement = doc.CreateElement("Title");

        //添加属性
        xmlElement.SetAttribute("ID", "21");
        xmlElement.SetAttribute("Name","王六");
        //将节点加入到指定的节点下
        XmlNode xml = doc.DocumentElement.PrependChild(xmlElement);
        doc.Save(path);
    }

或者是

 

 protected void Button3_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        string path = Server.MapPath("~/Title.xml");
        doc.Load(path);
        //创建节点
        XmlElement xmlElement = doc.CreateElement("Title");
        ////将节点加入到指定的节点下
        XmlNode xmlTitle = doc.DocumentElement.PrependChild(xmlElement);
        //为该节点加入属性
        XmlAttribute xmlID = doc.CreateAttribute("ID");
        xmlID.Value = "22";
        xmlTitle.Attributes.Append(xmlID);

        XmlAttribute xmlName = doc.CreateAttribute("Name");
        xmlName.InnerText = "小三";
        xmlTitle.Attributes.Append(xmlName);

        doc.Save(path);
    }

如果不需要创建节点,直接通过SelectSingleNode(string path)来获取XmlNode,然后再添加属性或者文本节点等,如下:

   protected void Button2_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        string path = Server.MapPath("~/XMLFile.xml");
        doc.Load(path);
        //创建一个book节点
        XmlNode xml = doc.SelectSingleNode("//TiTles//TiTle");
        XmlAttribute xmlAttribute = doc.CreateAttribute("ss");
        xmlAttribute.InnerText = "bb";
        xml.Attributes.Append(xmlAttribute);
        doc.Save(path);
    }

posted @ 2015-10-08 08:38  caijinhao  阅读(706)  评论(0编辑  收藏  举报