Write XML directly to disk and append elements

喜欢而已 提交于 2019-12-06 01:39:44

You can use an XmlTextWriter.

Just open the file for writing, seek back to the start of the end element, and then append any new elements you want with the XmlTextWriter. To close the file, simply write the raw text for the end element to make the document complete and you're done.

Here's a quick and dirty example.

Starting with XML like this:

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

You can open it and append an element like this:

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 is:

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

You may not get the indentation perfect etc, but it's valid XML. This is exactly what you'd do if writing xml as raw text to the file - but you might as well leverage the XML writer to do the formatting for you.

I'd also agree with some of the comments - it will be very beneficial to use a schema for your xml that minimises the size. Turn off indentation. Use the shortest element and attribute names you can. And if you are working on leaf elements, storing data as attributes rather than cdata will save room (<element>data</element> is more expensive than <element val="data"/> and this can be compressed further to <e v="data"/> - almost half the original size)

I would assume that (as @payo's comment suggests) you could use a combination of a file stream, an XmlTextReader (to position the stream at the appropriate element) and an XmlWriter to write the new elements and then re-write the closing element.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!