gpt4 book ai didi

c# - 省略 XML 声明?

转载 作者:行者123 更新时间:2023-12-05 02:23:31 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com