写入xml文件时的错误

yjk 2004-08-06 12:58:12
从程序中将数据写入一个xml的文件,发现不是我想要得格式,该怎样写呢。
代码如下:
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(XmlPath);
XmlElement PostElement = xmlDoc.CreateElement("Resource");

XmlElement Title = xmlDoc.CreateElement("Title",postToAdd.Subject);
XmlElement Creator = xmlDoc.CreateElement("Creator",postToAdd.Username);
XmlElement Type = xmlDoc.CreateElement("Type","Post");
XmlElement Identifier = xmlDoc.CreateElement("Identifier", newPost.ThreadID);

PostElement.AppendChild(Title);
PostElement.AppendChild(Creator);
PostElement.AppendChild(Type);
PostElement.AppendChild(Identifier);

//get the root element of the xml file
XmlElement root = xmlDoc.DocumentElement;
//add the PostElement as the child of root element
root.AppendChild(PostElement);

xmlDoc.Save(OutPath);

生成的结果如下
<?xml version="1.0" encoding="gb2312"?>
<Resources>
<Resource>
<Title xmlns="执子之手,与子偕老" />
<Creator xmlns="admin" />
<Type xmlns="Post" />
<Identifier xmlns="http://localhost/Forum/ShowPost.aspx?PostID=266" />
</Resource>
<Resources>
但我想要得结果是
<?xml version="1.0" encoding="gb2312"?>
<Resources>
<Resource>
<Title>执子之手,与子偕老</Title>
<Creator>admin</Creator>
<Type>Post</Type>
<Identifier>http://localhost/ShowPost.aspx?PostID=266</Identifier>
</Resource>
<Resources>
该怎么输出呢?
谢谢
...全文
334 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
yjk 2004-08-06
  • 打赏
  • 举报
回复
收到
baker_gw 2004-08-06
  • 打赏
  • 举报
回复
如果需要这类的XML输出,请考虑使用DataSet.WriteXml()方法。
思路:
1.数据存入DataSet;
2.DataSet直接保存为XML文件。
优点:避免了编写繁琐的XmlDocument相关程序。
我经常这样用,你也可以试试。
sneak 2004-08-06
  • 打赏
  • 举报
回复
Title.Value="执子之手,与子偕老";

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧