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

转载于:https://www.cnblogs.com/jinhaoObject/p/4860021.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值