I have a strange problem with my customer - I am reading an XML document (actually an InfoPath document) with XmlSerializer, modifying it, then writing out an XML document using the XmlSerializer, and then add some processing instructions by using the XmlTextWriter. All works well, and the resulting document is actually fully XML conform and can be read by InfoPath. One change that happens in the structure is however that the original document has all empty tags written in the form <A></A>, and when my document is written, it becomes <A/>. Actually exactly the same due to XML standards. But, my customer (a big company) apparently has some check/validation scripts with hardcoded <A></A>, and they fail. He's is now upset, and is too lazy to change his scripts, and wants the <A></A> notation! How can I setup XmlTextWriter to do it?
C# System.Xml.Serialization - use only <a></a> and never <a/>
124 Views Asked by Petr Osipov At
2
There are 2 best solutions below
0
On
Honestly I think if you're going to use the built in Serializer then you'd be better off doing a find/replace. It doesn't look like you can override the actual form of the tags, at least I've not seen a way to do it even overriding some of the methods.
As a result I would put a check in that says if a tag is empty, put in a value such as "[[[EMPTYVALUE]]]" so you end up with
<A>[[[EMPTYVALUE]]]</A>
Then generated your XML, and before saving the XML file, convert it to a string, and replace "<A>[[[EMPTYVALUE]]]</A>" with "<A></A>"
You could just do a replace on <A/> but I think it's safer to create a bigger string to replace.
You can do this by providing
XmlSerializerwith your ownXmlWriterdescendant, which would override theWriteEndElementmethod. By default, this method produces an empty element (<a />) or a closing element (</a>) depending on the contents of the element being output. You can change the behavior to always produce a full closing element.However, there's some more work needed, e.g. the
Asyncversion of this method, but in principle, it should be easy to achieve like above. I'd recommend looking into the source code ofXmlTextWriter.WriteEndElementand deriving a version that better fits your case.