How to check element name using WriteEndElement

I am writing xml with XmlWriter . There are many sections in my code:

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

The problem is that the ThirdPartyLibrary.Serialise method ThirdPartyLibrary.Serialise unreliable. It may happen (depending on the results variable) that it does not close all the tags that it opens. As a result, my WriteEndElement line is perverted, consumes closing the library widget tags, and doesnโ€™t write </payload> .

Thus, I would like to make a verified call to WriteEndElement, which checks the name of the element and throws an exception if the cursor is not in the expected element.

 xml.WriteEndElement("payload"); 

You can think of it as XmlReader.ReadStartElement(name) , which returns if the cursor is not at the expected location in the document.

How can I achieve this?


Edit: The second use case for this extension method is to make my own code more readable and reliable.

+7
source share
2 answers

In the end, I wrote a WriteSubtree extension method that gives this useful API:

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

The XmlWriter.WriteSubtree extension method is similar to .NET XmlReader.ReadSubtree . It returns a special XmlWriter that checks funny things. Its dispose method closes any tags that remain open.

0
source

XMLWriter simply writes xml data to the stream without any validation. If it does any validation when writing xml tags, a performance issue occurs when creating a large XML file.

Creating an XML file using XMLWriter is at the risk of the developer. If you want to do such a check, you can use XMLDocument.

If you really want to perform this check in XMLWriter, you need to create a record using String or StringBuilder. Because if you use Stream or TextWriter, you cannot read the information that is written to the stream in the middle of the message. In each XML update, you must read a line and write your own method to verify written information.

I suggest you use XMLDocument to create this type of xml.

+1
source

All Articles