简体   繁体   English

带有自定义格式的 C# XmlDocument

[英]C# XmlDocument with custom formatting

This code:这段代码:

XmlNode columnNode = null;                               
columnNode = xmlDoc.CreateElement("SYSID");
columnNode.InnerText = ""; // Empty string
newRowNode.AppendChild(columnNode);

...does this: ...做这个:

<SYSID>
</SYSID>

And I would like to have this, when string is empty:当字符串为空时,我想要这个:

<SYSID></SYSID>

Is there any solution?有什么解决办法吗?

If you have another tool that requires that format, then the other tool is wrong - it is incapable of reading XML.如果您有另一个需要该格式的工具,则另一个工具是错误的 - 它无法读取 XML。 So if you have control over the other tool, I'd suggest fixing it rather than trying to coerce your code into matching it.因此,如果您可以控制其他工具,我建议您修复它,而不是试图强制您的代码匹配它。

If you can't fix the other tool...如果您无法修复其他工具...

If you're just building a Document to write it out to disk, then you can use a stream and write the elements directly yourself (as simple text).如果您只是构建一个 Document 以将其写出到磁盘,那么您可以使用流并直接自己编写元素(作为简单文本)。 This will be faster (and may well be easier) than using an XmlDoc.这将比使用 XmlDoc 更快(并且可能更容易)。

As an improvement on that, you may be able to use an XmlWriter to write elements, but when you go to write an empty element, write raw text to the stream (ie writer.WriteRaw("<SYSID></SYSID>\\n")) so that you control the formatting for those particular elements.作为对此的改进,您可以使用 XmlWriter 来写入元素,但是当您要写入空元素时,请将原始文本写入流(即 writer.WriteRaw("<SYSID></SYSID>\\n ")) 以便您控制这些特定元素的格式。

If you need to build an in-memory XmlDocument, then to a large extent you have to put up with the formatting that it uses when you ask it to serialize to disk (aside from basic settings like PreserveWhitespace, you're asking the document to deal with storing the information, and so you lose a lot of control over the functionality that the XmlDocument encapsulates).如果您需要构建内存中的 XmlDocument,那么在很大程度上您必须忍受当您要求它序列化到磁盘时使用的格式(除了 PreserveWhitespace 等基本设置,您要求文档处理存储信息,因此您对 XmlDocument 封装的功能失去了很多控制)。 THe best suggestion I can think of in this case would be to write the XmlDocument to a MemoryStream and then post-process that memory stream to remove newlines from within empty elements.在这种情况下,我能想到的最佳建议是将 XmlDocument 写入 MemoryStream,然后对该内存流进行后处理以从空元素中删除换行符。 (Yuck!) (呸!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM