Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Fastest way to create an XML Document?

What's the fastest straightforward way to create a populated XMLDocument?

One mechanism is to do this:

StringWriter sw = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(sw);
xmlWriter.WriteLotsOfStuff...
xmlWriter.Close();
XmlDocument dom = new XmlDocument();
dom.LoadXml(sw.ToString());

But it just feels terribly wrong. Creating a string with some structured methods, then loading a DOM by parsing it. But the xmltextwriter methods are certainly far easier to use than the DOM methods of creating elements.

mb
Friday, August 13, 2004

DOM has a way of adding elements but you apparently already know those, so why do you ask? You think the CLR has another super-secret way of creating a DOM document somewhere?

Chris Nahr
Friday, August 13, 2004

i ask because the DOM methods are very clumsy and not really designed for creating a document, while the xmlwriter methods are pretty straightforward but output an intermediate stage which then takes CPU time to parse.

maybe there is some way to hook the two together which i just haven't noticed. not necessarily secret, there's just a lot of things in the framework.

for example, another way to do it is the use the xml serializer instead of the xml writer, but that may be even slower.

how do you create xml documents?

mb
Friday, August 13, 2004

MB - don't use a string/StringWriter as your backing store then. Have the XmlWriter wrap a MemoryStream or something then. Doing a .ToString() allocates a *new* string so don't do that and just keep it as a simple stream of bytes.

Duncan Smart
Sunday, August 15, 2004

In .NET 2.0 I like XPathDocuments.
The whole thing just feels more natural than the DOM.

I've stolen this example from the help:

XPathDocument document = new XPathDocument();
XPathEditableNavigator editor = document.CreateEditor();

using (XmlWriter writer = editor.PrependChild())
{
    writer.WriteStartElement("books");
    writer.WriteStartElement("book");
    writer.WriteAttributeString("published", null, "01-02-2003");
    writer.WriteAttributeString("isbn", null, "0-00-000000-0");
    writer.WriteElementString("title", "XPathDocument");
    writer.WriteElementString("author", "Author Name");
    writer.WriteElementString("pages", "150");
    writer.WriteEndElement();
    writer.WriteEndElement();
}

document.Save("books.xml");

Peter Ibbotson
Sunday, August 22, 2004

Xpath Document looks very much like reverse SAX.
:-) stw

Stephan H. Wissel
Sunday, September 05, 2004

*  Recent Topics

*  Fog Creek Home