Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check name of element with WriteEndElement

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.

like image 761
Colonel Panic Avatar asked Apr 04 '13 13:04

Colonel Panic


1 Answers

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.

like image 112
petchirajan Avatar answered Nov 04 '22 01:11

petchirajan