XmlDocument 不保留空格

XmlDocument not preserving whitespace

XmlDocument 在自闭合标签的末尾添加了一个 space,即使 PreserveWhitespace 设置为 true

// This fails
string originalXml = "<sample><node id=\"99\"/></sample>";

// Convert to XML
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(originalXml);

// Save back to a string
string extractedXml = null;

using (MemoryStream stream = new MemoryStream())
{
    doc.Save(stream);

    stream.Position = 0;
    using(StreamReader reader = new StreamReader(stream))
    {
        extractedXml = reader.ReadToEnd();
    }
}

// Confirm that they are identical
Assert.AreEqual(originalXml, extractedXml);

期望的输出是:

<sample><node id="99"/></sample>

但我得到:

<sample><node id="99" /></sample>

有没有办法抑制额外的 space?

下面是 XmlDocument.Save(Stream) 的样子:

public virtual void Save(Stream outStream)
{
  XmlDOMTextWriter xmlDomTextWriter = new XmlDOMTextWriter(outStream, this.TextEncoding);
  if (!this.preserveWhitespace)
    xmlDomTextWriter.Formatting = Formatting.Indented;
  this.WriteTo((XmlWriter) xmlDomTextWriter);
  xmlDomTextWriter.Flush();
}

所以设置PreserveWhiteSpace对节点内部没有影响。 XmlTextWriterdocumentation 表示:

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.

所以我想没有简单的出路。 Here 是一个解决方法:

So I wrote a wrapper class MtxXmlWriter that is derived from XmlWriter and wraps the original XmlWriter returned by XmlWriter.Create() and does all the necessary tricks.

Instead of using XmlWriter.Create() you just call one of the MtxXmlWriter.Create() methods, that's all. All other methods are directly handed over to the encapsulated original XmlWriter except for WriteEndElement(). After calling WriteEndElement() of the encapsulated XmlWriter, " />" is replaced with "/>" in the buffer: