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
Your first issue is that you don’t have XML – you have a stream of bytes which can be loaded into an
XDocumentorXmlDocument. Do you really need to output to a stream instead of directly into an XML Document?BTW, I think you need to lose the
usingblock around theMemoryStream. You won’t be able to use the stream for much after it’s been disposed.For efficiency, try to work directly with
XDocument. You seem to want to useXmlWriter, so here’s how to do it (not tested):Update:
You can write the XML with
Again, I can’t test it now, but try this: