C#读写XML的困惑

本文介绍了一个用于生成XML文件的C#类CreateXml,该类能够创建符合Google规范的网站地图XML文件,并提供了添加URL节点及保存XML文件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源代码如下:

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.....

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值