Search code examples
c#xelement

Omit XML declaration?


I have an XElement that I have to parse to remove the white space in the closing tag. My code looks like this:

var stringBuilder = new StringBuilder();
using (var stringWriter = new StringWriter(stringBuilder))
{
    xelement.Save(stringWriter);
}
stringBuilder.Replace(" />", "/>");
var xml = stringBuilder.ToString();

Basically, I'm making a stringbuilder and replacing the unneeded white space. The resulting string looks fine, except it has the XML declaration. I know that on an XmlWriter, I can omit the declaration with OmitXmlDeclaration but StringWriter doesn't have this.

Is there a way to do this, or do I need to manually parse out the declaration from the resulting string?

For clarity, here is the before and after XML:

// Before
<actionitem actiontaken="none" target="0" targetvariable="0">
  <windowname>Popup Window</windowname>
  <windowposx>-1</windowposx>
  <windowposy>-1</windowposy>
  <windowwidth>-1</windowwidth>
  <windowheight>-1</windowheight>
  <noscrollbars>false</noscrollbars>
  <nomenubar />
  <notoolbar />
  <noresize />
  <nostatus />
  <nolocation />
  <browserWnd />
</actionitem>

// After
<?xml version="1.0" encoding="utf-16"?>
<actionitem actiontaken="none" target="0" targetvariable="0">
  <windowname>Popup Window</windowname>
  <windowposx>-1</windowposx>
  <windowposy>-1</windowposy>
  <windowwidth>-1</windowwidth>
  <windowheight>-1</windowheight>
  <noscrollbars>false</noscrollbars>
  <nomenubar/>
  <notoolbar/>
  <noresize/>
  <nostatus/>
  <nolocation/>
  <browserWnd/>
</actionitem>

EDIT: For those that asked, this is for a Department of Defense project. Their specifications are locked in. That means, no white space in the closing tag, no matter how much I protest. Regardless of what's right or not, they don't want it, and they're signing the paycheck. I just try to accommodate them.


Solution

  • Use ToString() instead of Save(). That eliminates the need for the StringBuilder too.

     string xml = xelement.ToString(); // no declaration element added
     xml = xml.Replace(" />", "/>");   // if you really think you must