C#写XML的简单例子

来源:互联网 发布:微信选课系统源码 编辑:程序博客网 时间:2024/06/10 02:46

这个例子要把bookstore.xml文件增加一条book记录

1 bookstore.xml

 

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="love" ISBN="1234123">
    <title>who am i </title>
    <author>who</author>
    <price>999</price>
  </book>
</bookstore>

 

2 bookstore.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace toxml
{
    public class ToXml
    {
        public static void Main(string[] args)
        {
            //实例化一个XmlDocument对象
            XmlDocument xmlDoc = new XmlDocument();
            //实例对象读取要写入的XML文件
            xmlDoc.Load("bookstore.xml");
            //查找<bookstore>
            XmlNode root = xmlDoc.SelectSingleNode("bookstore");
            //创建一个<book>节点
            XmlElement xe1 = xmlDoc.CreateElement("book");
            //设置该节点genre属性
            xe1.SetAttribute("leixing", "music");
            //设置该节点ISBN属性   
            xe1.SetAttribute("ISBN", "56756");
            //设置标题子节点
            XmlElement xesub1=xmlDoc.CreateElement("title");
            //设置文本内容
            xesub1.InnerText = "CS从入门到精通";
            //将文本内容添加到<book>节点中
            xe1.AppendChild(xesub1);
            //添加作者子结点
            XmlElement xesub2 = xmlDoc.CreateElement("author");
            //设置作者名字
            xesub2.InnerText = "候捷";
            //将文本内容添加到<book>节点中
            xe1.AppendChild(xesub2);
            //添加价格子结点
            XmlElement xesub3 = xmlDoc.CreateElement("price");
            //设置价格
            xesub3.InnerText = "222";
            //将价格添加到<book>节点中
            xe1.AppendChild(xesub3);
            //添加到<bookstore>节点中
            root.AppendChild(xe1);
            //保存文件
            xmlDoc.Save("bookstore.xml");
        }
    }
}

 

运行后的XML文件如下:

 

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="love" ISBN="1234123">
    <title>who am i </title>
    <author>who</author>
    <price>999</price>
  </book>
  <book leixing="music" ISBN="56756">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>222</price>
  </book>
</bookstore>

原创粉丝点击