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

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

内容简介:翻译自: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


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

查看所有标签

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

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov / O'Reilly Media, Inc. / 2010-09-21 / USD 29.99

What's the best approach for developing an application with JavaScript? This book helps you answer that question with numerous JavaScript coding patterns and best practices. If you're an experienced d......一起来看看 《JavaScript Patterns》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码