c# - 在不缓冲到 RAM 的情况下将元素复制和附加到 XML 文档

标签 c# xml

如标题所示,我需要将日志数据附加到 XML 文件而不缓冲到 RAM。 XML 文件由 LogEntry 元素组成,其中包含 82 个包含数据的子元素。这些文件可能会变得非常大,因为它将构成 Windows CE6 程序的一部分,我们的内存非常有限。

经过大量研究后,很明显最常用的方法是使用 XDocumentLinq to XML 在附加到现有文档之前读取现有文档,然后写出新文件。同时使用 XmlWriterXmlReader 似乎是我追加到文件的最佳方式,但到目前为止我的所有尝试都非常不切实际,需要 IF 语句来指示什么写入以防止写入重复或数据较少的元素。

我所做的本质是:

//Create an XmlReader to read current WorkLog.
using (XmlReader xmlRead = XmlTextReader.Create("WorkLog.xml"))
{
   //Create a XmlWriterSettings and set indent 
   //to true to correctly format the document
   XmlWriterSettings writerSettings = new XmlWriterSettings();
   writerSettings.Indent = true;
   writerSettings.IndentChars = "\t";

   //Create a new XmlWriter to output to
   using (XmlWriter xmlWriter = XmlWriter.Create("New.xml", writerSettings))
   {
      //Starts the document
      xmlWriter.WriteStartDocument();

      //While the XmlReader is still reading (essentially !EOF)
      while (xmlRead.Read())
      {
         //FSM to direct writing of OLD Log data to new file
         switch (xmlRead.NodeType)
         {
            case XmlNodeType.Element:
               //Handle the copying of an element node
               //Contains many if statements to handle root node &  
               //attributes and to skip nodes that contain text
               break;
            case XmlNodeType.Text:
               //Handle the copying of an text node
               break;
            case XmlNodeType.EndElement: 
               //Handle the copying of an End Element node
               break;
         }
      }

      xmlWriter.WriteEndDocument();
   }
}

我相信我可以通过这种方式追加到文件,但这样做非常不切实际 - 有谁知道我的搜索时间没有出现的任何内存有效方法吗?

如果需要,我很乐意发布我当前的代码来执行此操作 - 但正如我所提到的,它非常大,目前实际上非常讨厌,所以我暂时将其搁置。

最佳答案

如果您知道自己的 xml 结构,请考虑使用流编写器。 1.打开文件为文件流 2. 将点移动到您要替换的标签,例如:,将您的点(位置)移动到“<” 3. 以正确的xml格式写入你的日志数据并在写入末尾写入“”

“用文本编辑器处理xml文件”

关于c# - 在不缓冲到 RAM 的情况下将元素复制和附加到 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16191015/

相关文章:

c# - 如何将类(class)添加到列表中?

java - xml转json再转回xml返回错误

java - Jackson List<Map<String, String>> 到 xml

c# - 在代码隐藏中设置 Eval

c# - 关于基于ServiceStack的服务类型命名的问题

java - 如何使用 Citrus 框架验证 JSON 中嵌入的 XML?

xml - 在 C# 中从 XML 中删除所有属性的最简单方法是什么?

javascript - cheeriojs 迭代 xml 响应

c# - 为什么 MVC 在 GET 上使用模型状态而不是提供的模型

c# - 将 JSON 字符串中的数据覆盖到现有对象实例