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();
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"/> - )