Fastest way to add new node to end of an xml?

前端 未结 10 684
深忆病人
深忆病人 2020-11-29 10:21

I have a large xml file (approx. 10 MB) in following simple structure:


   .......
   .......         


        
10条回答
  •  眼角桃花
    2020-11-29 11:13

    You need to use the XML inclusion technique.

    Your error.xml (doesn't change, just a stub. Used by XML parsers to read):

    
    
    ]>
    
    &logrows;
    
    

    Your errorrows.txt file (changes, the xml parser doesn't understand it):

    ....
    ....
    ....
    

    Then, to add an entry to errorrows.txt:

    using (StreamWriter sw = File.AppendText("logerrors.txt"))
    {
        XmlTextWriter xtw = new XmlTextWriter(sw);
    
        xtw.WriteStartElement("Error");
        // ... write error messge here
        xtw.Close();
    }
    

    Or you can even use .NET 3.5 XElement, and append the text to the StreamWriter:

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

    See also Microsoft's article Efficient Techniques for Modifying Large XML Files

提交回复
热议问题