Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we force XmlWriter to issue <my-tag></my-tag> rather than <my-tag/>?

By default,

someXmlWriter.WriteElementString("my-tag", someString); 

produces <my-tag />

I looked around XmlWriterSettings class for possible options that would force the writer to produce <my-tag></my-tag> instead but didn't find anything.

Is there a simple way of forcing the XmlWriter to issuing empty elements with "open tag, close tag" rather than with the short-hand form?

Edit:
Yes! I realize that with regards to XML validity the two notations are equivalent, valid and all... I'm however working with legacy code which parses such XML using Read(), i.e. at node level (!) and fumbles things up by Read()-ing when on an empty node...

Hence my question comes in the context of limiting the amount of changes to this legacy code. The question is indeed overlapping with this SO question as suggested; none of the options offered there are however easily applicable to my situation.

like image 661
mjv Avatar asked Jan 25 '12 21:01

mjv


2 Answers

This worked for me:

writer.WriteStartElement("my-tag"); writer.WriteRaw(someString); writer.WriteFullEndElement(); 

WriteEndElement still self closed the tag

like image 135
mejobloggs Avatar answered Oct 15 '22 22:10

mejobloggs


If you get the message Extension method can only be declared in non-generic, non-nested static class as the word this may be highlighted, simply create an extension class as shown below:

public static class Extension {     public static void WriteFullElementString(this XmlTextWriter writer, string localName, string value)     {         writer.WriteStartElement(localName);         writer.WriteRaw(value);         writer.WriteFullEndElement();     } } 

Hope this proves useful :-)

like image 38
iggyweb Avatar answered Oct 15 '22 23:10

iggyweb