matthew Zhang

慢慢学习,慢慢进步!
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

添加XML记录的方法

Posted on 2008-10-31 22:07  matthewZhang  阅读(244)  评论(0编辑  收藏  举报

【引自】http://www.alixixi.com

今天写代码,添加几条XML记录,总感觉写那几条重复的语句很不爽,就写了这个方法

代码如下:

private void addXmlInfo(string xmlPath,string rootElement,string rootPoint,int elementNum,string[,] addInfo)
{
        XmlDocument xdt = new XmlDocument();
        xdt.Load(Server.MapPath(xmlPath));
        XmlNode root = xdt.SelectSingleNode(rootElement);
        XmlElement rootly = xdt.CreateElement(rootPoint);
        for(int i=0;i<elementNum;i++)
        {
                XmlElement[] temp = new XmlElement[elementNum];
                temp = xdt.CreateElement(addInfo[i,0]);
                temp.InnerText = addInfo[i,1];
                rootly.AppendChild(temp);
        }
        root.AppendChild(rootly);
        xdt.Save(Server.MapPath(xmlPath));
}

 


方法有5个参数,下面介绍下这5个参数:

参数一 xmlPath , string型 , 代表XML文档的相对路径
参数二 rootElement , string型 , 代表XML文档的根元素
参数三 rootPoint , string型 , 代表XML文档每条记录的根元素
参数四 elementNum , int型 , 代表每条记录的子元素数量
参数五 addInfo , 数组型 , 代表的是一个二维数组,用来存储每条记录的信息,包括元素名和元素的值

下面给个例子:

用来演示的XML文档结构如下:
<?xml version="1.0" encoding="utf-8"?>
<ProgramboyGuestbook>
  <ly>
    <Gcontent>这是用来演示插入XML记录方法的XML文档,我的相对路径是Data/test.xml</Gcontent>
    <Gname>孤鸿</Gname>
    <Gtime>2006-9-18 8:49:23</Gtime>
    <Gweb>http://www.programboy.com</Gweb>
  </ly>
</ProgramboyGuestbook>

下面我们来调用插入方法,实现插入操作:

this.addXmlInfo("Data/test.xml","ProgramboyGuestbook","ly",4,new string[,] {{"Gcontent",theContent},{"Gname",theName},{"Gtime",theTime},{"Gweb",theWeb}});