【问题标题】:Inserting new data into xml from datatable将新数据从数据表插入 xml
【发布时间】:2017-08-03 06:57:58
【问题描述】:

我有一个大约 900MB 的 xml 文件,我想将数据表中的数据插入到现有的 xml 中。

有一种方法可以通过使用加载和保存来做到这一点,如下所示;

XDocument xdoc = XDocument.Load(FilePath);
var root = xdoc.Descendants("DocumentElement").FirstOrDefault()
if (root != null){
    root.Add(new XElement("tag", "value"));
    xdoc.Save(FilePath);
}

但是,它的成本太高了。将 900MB 的 xml 加载到数据表中可能会导致内存异常和几个新行的性能下降。

如何从数据表中向现有的大型 xml 添加新行?

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    XDocument(以及XmlDocument)将整个文件加载到内存中。您应该使用XmlWriterXNode.WriteTo 方法的组合

    来自XNode.WriteTo 文档的示例:

    StringBuilder sb = new StringBuilder();
    XmlWriterSettings xws = new XmlWriterSettings();
    xws.OmitXmlDeclaration = true;
    xws.Indent = true;
    
    using (XmlWriter xw = XmlWriter.Create(sb, xws)) 
    {
       XElement child2 = new XElement("AnotherChild",
        new XElement("GrandChild", "different content"));
       child2.WriteTo(xw);
       xw.WriteEndElement();
    }
    
    Console.WriteLine(sb.ToString());
    

    你可以用同样的方式读取大的 xml 文档,查看XNode.ReadFrom文档中的示例

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      相关资源
      最近更新 更多