简体   繁体   English

将空XML元素渲染为父元素

[英]Render Empty XML Elements as Parent Elements

I have a strange requirement where an application consuming some XML that my application is generating actually needs empty elements to be serialized as parent elements. 我有一个奇怪的要求,即我的应用程序生成的消耗一些XML的应用程序实际上需要将空元素序列化为父元素。 For example: 例如:

<element foo="bar" />

should be: 应该:

<element foo="bar"></element>

I'm not aware of any way that the XmlSerializer allows you to change this. 我不知道XmlSerializer允许你改变它的任何方式。 Does anybody know how to accomplish this? 有人知道怎么做到这一点吗?

I extended XmlTextWriter so that I could override the WriteEndElement() method, forcing it to call WriteFullEndElement(). 我扩展了XmlTextWriter,以便我可以覆盖WriteEndElement()方法,强制它调用WriteFullEndElement()。 This did the trick. 这样做了。

Note: for anybody that saw my question update, please ignore. 注意:对于任何看到我的问题更新的人,请忽略。 IE was rendering the XML in the shorthand form. IE以简写形式呈现XML。 As soon as I opened it in Notepad, I realized everything was working fine. 当我在记事本中打开它时,我意识到一切正常。

public class FullEndingXmlTextWriter : XmlTextWriter
{
    public FullEndingXmlTextWriter(TextWriter w)
        : base(w)
    {
    }

    public FullEndingXmlTextWriter(Stream w, Encoding encoding)
        : base(w, encoding)
    {
    }

    public FullEndingXmlTextWriter(string fileName, Encoding encoding)
        : base(fileName, encoding)
    {
    }

    public override void WriteEndElement()
    {
        this.WriteFullEndElement();
    }
}

You could solve it with a regular expression, making it a two-pass process. 您可以使用正则表达式解决它,使其成为两遍过程。

string xml = "element foo=\"bar\" />"

string pattern = @"<(?<elem>\w+)(?<body>\b.*)/>";
string substitute =  @"<${elem} ${body}></${elem}>";

Regex regex = new Regex(pattern);
string goodresult = regex.Replace(xml, substitute);

Scott Hanselman wrote a while back an article about stripping out empty elements from XML, and at a glance the code can be used for your purpose with a small alteration to the treatment of empty elements. Scott Hanselman不久前写了一篇关于从XML中删除空元素的文章,一目了然,代码可以用于您的目的,只需对空元素的处理进行一些小改动。 He also explains why using RegEx is a bad idea. 他还解释了为什么使用RegEx是一个坏主意。

I am pointing this out, as I don't know of a way to get XmlSerializer to do what you want. 我指出这一点,因为我不知道如何让XmlSerializer做你想做的事。

Another possibility, though I don't really know much about WPF is using the XAML serializer - look at the System.Window.Markup namespace documentation. 另一种可能性,虽然我对WPF并不太了解,但是使用XAML序列化程序 - 请查看System.Window.Markup命名空间文档。

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

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