Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a XmlDocument using XmlWriter in .NET?

Many .NET functions use XmlWriter to output/generate xml. Outputting to a file/string/memory is a very operation:

XmlWriter xw = XmlWriter.Create(PutYourStreamFileWriterEtcHere); xw.WriteStartElement("root"); ... 

Sometimes , you need to manipulate the resulting Xml and would therefore like to load it into a XmlDocument or might need an XmlDocument for some other reason but you must generate the XML using an XmlWriter. For example, if you call a function in a 3rd party library that outputs to a XmlWriter only.

One of the things you can do is write the xml to a string and then load it into your XmlDocument:

StringWriter S = new StringWriter(); XmlWriter xw = XmlWriter.Create(S); /* write away */ XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(S.ToString()); 

However this is inefficient - first you serialize all the xml info into a string, then you parse the string again to create the DOM.

How can you point an XmlWriter to build a XmlDocument directly?

like image 946
Boaz Avatar asked Aug 28 '09 13:08

Boaz


People also ask

How do you create an XmlWriter?

Creates a new XmlWriter instance using the stream and XmlWriterSettings object. Creates a new XmlWriter instance using the specified XmlWriter and XmlWriterSettings objects. Creates a new XmlWriter instance using the specified StringBuilder. Creates a new XmlWriter instance using the specified filename.

What is XmlWriter C#?

XmlWriter represents a writer that provides a fast, non-cached, forward-only way to generate streams or files with XML. The XmlWriter is available in the System. Xml namespace.

What is XmlDocument in C#?

The XmlDocument represents an XML document. It can be use to load, modify, validate, an navigate XML documents. The XmlDocument class is an in-memory representation of an XML document. It implements the W3C XML Document Object Model (DOM).


1 Answers

Here's at least one solution:

XmlDocument doc = new XmlDocument();  using (XmlWriter writer = doc.CreateNavigator().AppendChild())  {      // Do this directly       writer.WriteStartDocument();       writer.WriteStartElement("root");       writer.WriteElementString("foo", "bar");       writer.WriteEndElement();       writer.WriteEndDocument();     // or anything else you want to with writer, like calling functions etc. } 

Apparently XpathNavigator gives you a XmlWriter when you call AppendChild()

Credits go to Martin Honnen on : http://groups.google.com/group/microsoft.public.dotnet.xml/browse_thread/thread/24e4c8d249ad8299?pli=1

like image 82
Boaz Avatar answered Sep 24 '22 16:09

Boaz