Burn XML directly to disk and add elements

I am trying to write an XML file, but it is too large to hold in memory, so I want to write it directly to disk. I tried using XmlWriter, but there is no way to include the application at the end of the file, so I am ready to resort to writing an XML file using a regular writer file.

Does anyone know of any file writing classes that allow me to write directly to disk and that allow me to overwrite positions within a file?

The reason is that I need to write over closing the root element so that I can add another bit of information, but also be able to read the XML file when necessary. For example, if I had the following XML:

<elements>
  <element>
  </element>
</elements>

If I wanted to read this, I could, but if I wanted to write it, I must first remove the tag </elements>, add another element and add the closing tag again.

Thanks for any help.

+3
source share
2 answers

You can use XmlTextWriter.

Just open the file for writing, go back to the beginning of the end element and add the new elements you want using XmlTextWriter. To close the file, simply write the source code for the final element so that the document is complete and you're done.

Here is a quick and dirty example.

Starting with XML as follows:

<?xml version="1.0" encoding="utf-8"?>
<DocumentElement>
    <FirstElem/>
</DocumentElement>

You can open it and add such an element:

using (FileStream f = new FileStream(@"D:\a.xml", FileMode.OpenOrCreate, FileAccess.Write))
{
    f.Seek(-("</DocumentElement>\n".Length), SeekOrigin.End);
    using (XmlTextWriter x = new XmlTextWriter(f, Encoding.UTF8))
    {
        x.WriteStartElement("Another");
        x.WriteAttributeString("attr", "value");
        x.WriteEndElement();

        // Close the file with a new terminating end-element
        x.WriteRaw("\r\n</DocumentElement>\r\n");
    }
}

And the result:

<?xml version="1.0" encoding="utf-8"?>
<DocumentElement>
    <FirstElem/>
<Another attr="value" />
</DocumentElement>

.., XML. , , xml , XML-writer .

- xml, . . . , , cdata, (<element>data</element> , <element val="data"/>, <e v="data"/> - )

+4

, ( @payo) , XmlTextReader ( ) XmlWriter , .

+1

All Articles