How to append new elements to Xml from a stream

Posted by Wololo on Stack Overflow See other posts from Stack Overflow or by Wololo
Published on 2010-03-20T02:37:16Z Indexed on 2010/03/20 3:01 UTC
Read the original article Hit count: 403

Filed under:
|
|

I have a method which returns some xml in a memory stream

private MemoryStream GetXml()
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;

    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("root");
            writer.WriteStartElement("element");
            writer.WriteString("content");
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
        }

        return memoryStream;
    }
}

In this example the format of the xml will be:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>content</element>
</root>

How can i insert a new element under the root e.g

<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>content</element>
  ----->New element here <------
</root>

EDIT:

Also please suggest the most efficient method as returning a memorystream may not be the best solution.

The final xml will be passed to a custom HttpHandler so what are the best options for writing the output?

context.Response.Write vs context.Response.OutputStream

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml