Question

I'm writing xml with XmlWriter. My code has lots of sections like this:

xml.WriteStartElement("payload");
ThirdPartyLibrary.Serialise(results, xml);
xml.WriteEndElement(); // </payload>

The problem is that the ThirdPartyLibrary.Serialise method is unreliable. It can happen (depending on the variable results) that it doesn't close all the tags it opens. As a consequence, my WriteEndElement line is perverted, consumed closing the library's hanging tags, rather than writing </payload>.

Thus I'd like to make a checked call to WriteEndElement that checks the element name, and throws an exception unless the cursor is at the expected element.

xml.WriteEndElement("payload");

You can think of this like XmlReader.ReadStartElement(name) which throws unless the cursor is at the expected place in the document.

How can I achieve this?


Edit: A second use case for this extension method would be to make my own code more readable and reliable.

Was it helpful?

Solution 2

In the end, I wrote an extention method WriteSubtree that gives this usable API:

using (var resultsXml = xml.WriteSubtree("Results"))
{
    ThirdPartyLibrary.Serialise(results, resultsXml);
}

The extension method XmlWriter.WriteSubtree is analogous to .NET's XmlReader.ReadSubtree. It returns a special XmlWriter that checks against funny business. Its dispose method closes any tags left open.

OTHER TIPS

XMLWriter is just writes the given xml information in the stream with out any validation. If it does any validation while writing the xml tags, the performance problem will arise while creating the big xml file.

Creating the XML file using XMLWriter is up to developer risk. If you want to do any such kind of validation, you can use XMLDocument.

If you really want to do this validation in XMLWriter, you have to create the writer by using String or StringBuilder. Because, if you use Stream or TextWriter you can't read the information which is written into the stream in the middle of writing. In Every update of the XML you have to read the string and write your own method to validate the written information.

I Suggest you to use XMLDocument for creating these type of xml.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top