c# – 将新节点添加到xml结尾的最快方法?

栏目: ASP.NET · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/849043/fastest-way-to-add-new-node-to-end-of-an-xml

我有一个大的xml文件(大约10 MB)以下简单的结构:

<Errors>
   <Error>.......</Error>
   <Error>.......</Error>
   <Error>.......</Error>
   <Error>.......</Error>
   <Error>.......</Error>
</Errors>

我需要写一个新节点<Error>在</ Errors>之前的末尾标签.什么是在.net中实现这一目标的最快方法?

您需要使用XML包含技术.

你的error.xml(不会改变,只是一个存根.由XML解析器用来读取):

<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY logrows    
 SYSTEM "errorrows.txt">
]>
<Errors>
&logrows;
</Errors>

你的errorsrows.txt文件(更改,xml解析器不理解它):

<Error>....</Error>
<Error>....</Error>
<Error>....</Error>

然后,向errorsrows.txt添加一个条目:

using (StreamWriter sw = File.AppendText("logerrors.txt"))
{
    XmlTextWriter xtw = new XmlTextWriter(sw);

    xtw.WriteStartElement("Error");
    // ... write error messge here
    xtw.Close();
}

或者您甚至可以使用.NET 3.5 XElement,并将文本附加到StreamWriter:

using (StreamWriter sw = File.AppendText("logerrors.txt"))
{
    XElement element = new XElement("Error");
    // ... write error messge here
    sw.WriteLine(element.ToString());
}

另见 Microsoft’s article Efficient Techniques for Modifying Large XML Files

翻译自:https://stackoverflow.com/questions/849043/fastest-way-to-add-new-node-to-end-of-an-xml


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Design for ROI

Web Design for ROI

Lance Loveday、Sandra Niehaus / New Riders Press / 2007-10-27 / USD 39.99

Your web site is a business--design it like one. Billions of dollars in spending decisions are influenced by web sites. So why aren't businesses laser-focused on designing their sites to maximize thei......一起来看看 《Web Design for ROI》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具