默认情况下,
someXmlWriter.WriteElementString("my-tag", someString);
生成
我环顾四周 XmlWriterSettings 类,用于强制编写器生成
的可能选项相反但是没有找到任何东西。
有没有一种简单的方法来强制 XmlWriter 使用“打开标签,关闭标签”而不是使用简写形式发出空元素?
编辑:
是的!我意识到,就 XML 有效性而言,这两个符号是等效的、有效的并且都是...但是,我正在使用旧代码,该代码使用 Read() 解析此类 XML,即在节点级别(!)并通过 Read 搞乱事情()-ing 在空节点上时...
因此,我的问题是在限制对此遗留代码的更改量的背景下出现的。这个问题确实与建议的这个问题重叠;然而,那里提供的选项都不能轻易适用于我的情况。
By default,
someXmlWriter.WriteElementString("my-tag", someString);
produces <my-tag />
I looked around XmlWriterSettings class for possible options that would force the writer to produce <my-tag></my-tag>
instead but didn't find anything.
Is there a simple way of forcing the XmlWriter to issuing empty elements with "open tag, close tag" rather than with the short-hand form?
Edit:
Yes! I realize that with regards to XML validity the two notations are equivalent, valid and all... I'm however working with legacy code which parses such XML using Read(), i.e. at node level (!) and fumbles things up by Read()-ing when on an empty node...
Hence my question comes in the context of limiting the amount of changes to this legacy code. The question is indeed overlapping with this SO question as suggested; none of the options offered there are however easily applicable to my situation.
发布评论
评论(7)
把它留在这里以备不时之需;因为上面的答案都没有为我解决这个问题,或者看起来有点矫枉过正。
诀窍是设置XmlWriterSettings.Indent = true并将其添加到XmlWriter。
编辑:
或者,您也可以使用
XmlWriterSettings 来代替添加。
Leaving this here in case someone needs it; since none of the answers above solved it for me, or seemed like overkill.
The trick was to set the XmlWriterSettings.Indent = true and add it to the XmlWriter.
Edit:
Alternatively you can also use
instead of adding an XmlWriterSettings.
我刚刚遇到了同样的问题,虽然这看起来像是一种黑客攻击,但这确实有效,并且对我必须使用的现有代码非常不干扰。
I just ran into this exact same issue, and while it seems like kind of a hack, this did indeed work and was very unintrusive to the existing code I had to work with.
这对我有用:
WriteEndElement 仍然自动关闭标签
This worked for me:
WriteEndElement still self closed the tag
如果您收到消息
扩展方法只能在非泛型、非嵌套静态类中声明
,因为单词this
可能会突出显示,只需创建一个扩展类,如图所示如下:希望这有用:-)
If you get the message
Extension method can only be declared in non-generic, non-nested static class
as the wordthis
may be highlighted, simply create an extension class as shown below:Hope this proves useful :-)
试试这个:
Try this:
我使用下一个代码:
I use the next code:
您是否尝试过这样的事情:
也许用它作为成员函数创建一个实用程序类。
Have you tried something like this:
Maybe make a utility class with that as a member function.