C# System.Xml.Serialization - use only <a></a> and never <a/>

124 Views Asked by At

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?

2

There are 2 best solutions below

4
Ondrej Tucny On BEST ANSWER

You can do this by providing XmlSerializer with your own XmlWriter descendant, which would override the WriteEndElement method. 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.

public class MyXmlWriter : XmlTextWriter
{
    // …constructors etc. omitted for the sake of simplicity…

    public override void WriteEndElement()
    {
        // this should do the trick
        WriteFullEndElement();
    }
}

However, there's some more work needed, e.g. the Async version of this method, but in principle, it should be easy to achieve like above. I'd recommend looking into the source code of XmlTextWriter.WriteEndElement and deriving a version that better fits your case.

0
NibblyPig 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.