c# - 省略 XML 声明?

标签 c# xelement

我有一个 XElement,我必须解析它以删除结束标记中的空白。我的代码如下所示:

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

基本上,我正在制作一个 stringbuilder 并替换不需要的空白。生成的字符串看起来不错,除了它有 XML 声明。我知道在 XmlWriter 上,我可以使用 OmitXmlDeclaration 省略声明,但 StringWriter 没有这个。

有没有办法做到这一点,还是我需要手动从结果字符串中解析出声明?

为清楚起见,这里是 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>

编辑:对于那些提出要求的人,这是针对国防部的一个项目。他们的规范被锁定。这意味着,无论我多么反对,结束标签中都没有空白。不管什么对不对,他们都不想要,他们签了薪水。我只是尽量适应他们。

最佳答案

使用 ToString() 而不是 Save()。这也消除了对 StringBuilder 的需要。

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

关于c# - 省略 XML 声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21837929/

相关文章:

c# - 向 XElement 添加空白行以保留其他格式

c# - 将 XML 字符串添加到 XElement

C# 正在自行舍入除法

c# - 当 MSMQ 服务器重新启动时,远程 MSMQ 连接显然丢失问题

c# - 从 IDbCommandInterceptor 的实现中获取 DbContext

c# - 使用 C# 类中的填充值生成模拟 XML 的工具

c# - 用等效字符串表示 Char

xml - 如何获取 <?来自 xml 的标签与 vb.net

.net - 如何将 XPath 与 XElement 或 LINQ 一起使用?

c# - 使用 LINQ 从 XML 中选择多个节点