C#读写XML的困惑

源代码如下:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;

namespace GoogleSite
{
 /// <summary>
 /// CreateXml 的摘要说明。
 /// </summary>
 public class CreateXml
 {
  private string path;
  private string fileName;
  private XmlDocument xmlDoc;
  private XmlNode urlsetNode;
  private XmlElement urlNode;
  #region
  public CreateXml()
  {
   init();
  }
  #endregion

  #region 属性
  /// <summary>
  /// 保存路径
  /// </summary>
  public string Path
  {
   get
   {
    return path;
   }
   set
   {
    path=value;
   }
  }

  /// <summary>
  /// 保存XML文件的文件名
  /// </summary>
  public string FileName
  {
   get
   {
    return fileName;
   }
   set
   {
    fileName=value;
   }
  }
  #endregion

  private void init()
  {
   xmlDoc=new XmlDocument();
   XmlNode xmlNode=xmlDoc.CreateXmlDeclaration("1.0","UTF-8","");
   xmlDoc.AppendChild(xmlNode);
   urlsetNode=xmlDoc.CreateNode(XmlNodeType.Element,"urlset","http://www.google.com/");
   xmlDoc.AppendChild(urlsetNode);
  }

  public void AppendUrlNode(string loc,string lastmod,string changefreq,string priority)
  {
   urlsetNode.AppendChild(CreateUrlNode(loc,lastmod,changefreq,priority));
  }

  private XmlElement CreateUrlNode(string loc,string lastmod,string changefreq,string priority)
  {
   urlNode=xmlDoc.CreateElement("","url","");
   //添加loc节点
   XmlElement locNode=xmlDoc.CreateElement("","loc","");
   locNode.InnerText=loc;
   

   //添加lastmod节点
   XmlElement lastmodNode=xmlDoc.CreateElement("","lastmod","");
   lastmodNode.InnerText=lastmod;
   
   //添加changefreq节点
   XmlElement changefreqNode=xmlDoc.CreateElement("","changefreq","");
   changefreqNode.InnerText=changefreq;
   
   //添加priority节点
   XmlElement priorityNode=xmlDoc.CreateElement("","priority","");
   priorityNode.InnerText=priority;

   urlNode.AppendChild(locNode);
   urlNode.AppendChild(lastmodNode);
   urlNode.AppendChild(changefreqNode);
   urlNode.AppendChild(priorityNode);

   return urlNode;
  }

  public void SaveXmlFile()
  {
       this.AppendUrlNode("loc","lastmod","changefreq","priority");
   
   try
   {
    xmlDoc.Save(@"D:/sitemap.xml");
    MessageBox.Show("保存完成!");
   }
   catch(Exception e)
   {
    MessageBox.Show(e.Message);
   }
  }


 }
}
 最后生成的结果:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/">
  <url xmlns="">
    <loc>loc</loc>
    <lastmod>lastmod</lastmod>
    <changefreq>changefreq</changefreq>
    <priority>priority</priority>
  </url>
</urlset>

这里有一点非常不理解,同样是CreateElement()方法,CreateElement("","loc","")没有带有“xmlns”字段,而CreateElement("","url","")却带有 xmlns="http://www.google.com/"这一属性(本不需要),不知道为什么,也不知道如何解决,郁闷ing.....

posted @ 2006-09-25 11:56  周金桥  阅读(228)  评论(0编辑  收藏  举报