开发者

Remove whitespace in self closing tags when writing xml document

开发者 https://www.devze.com 2023-03-17 14:25 出处:网络
When writing out an xml document I need to write all self closing tags without any whitespace, for example:

When writing out an xml document I need to write all self closing tags without any whitespace, for example:

<foo/> 

instead of:

<foo />

The reason for this is that a vendor system that I'm interfacing with throws a fit otherwise. In an ideal world the vendor would fix their system, but I don't bet on that happening any time soon. What's the best way to get an XmlWriter to output the self closing tags without the space?

My current scheme is to do something like:

return xml.Replace(" />", "/>");

Obviously thi开发者_JS百科s is far from ideal. Is it possible to subclass the XmlWriter for that one operation? Is there a setting as part of the XmlWriterSettings that I've overlooked?


I think that there is no such option to avoid that one space in self-closing tag. According to MSDN, XmlTextWriter:

When writing an empty element, an additional space is added between tag name and the closing tag, for example . This provides compatibility with older browsers.

Hopefully you could write <elementName></elementName> syntax instead of unwanted <elementName />, to do that use XmlWriter.WriteFullEndElement method, e.g.:

using System.Xml;
..

static void Main(string[] args)
{
    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
    xmlWriterSettings.Indent = true;
    xmlWriterSettings.IndentChars = ("\t");
    xmlWriterSettings.OmitXmlDeclaration = true;
    XmlWriter writer = XmlWriter.Create("example.xml", xmlWriterSettings);

    writer.WriteStartElement("root");

    writer.WriteStartElement("element1");
    writer.WriteEndElement();

    writer.WriteStartElement("element2");
    writer.WriteFullEndElement();

    writer.WriteEndElement();
    writer.WriteEndDocument();
    writer.Close();
}

produces following XML document:

<root>
    <element1 />
    <element2></element2>
</root>


Use a different serializer, for example the Saxon serializer, which also runs on .NET. It so happens that the Saxon serializer does what you want.

It's horrible, of course, to choose products based on accidental behaviour that no self-respecting system would require, but you have to accept reality - if you want to trade with idiots, you have to behave like an idiot.


Try this:

 x.WriteStartElement("my-tag"); 

//Value of your tag is null
If (<"my-tag"> == "")
{
 x.WriteWhitespace("");
}else
 x.WriteString(my-tag);

x.WriteEndElement();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号