Render Empty XML Elements as Parent Elements

限于喜欢 提交于 2019-12-20 04:34:51

问题


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. 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. Does anybody know how to accomplish this?


回答1:


I extended XmlTextWriter so that I could override the WriteEndElement() method, forcing it to call WriteFullEndElement(). This did the trick.

Note: for anybody that saw my question update, please ignore. IE was rendering the XML in the shorthand form. 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();
    }
}



回答2:


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);



回答3:


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. He also explains why using RegEx is a bad idea.

I am pointing this out, as I don't know of a way to get XmlSerializer to do what you want.

Another possibility, though I don't really know much about WPF is using the XAML serializer - look at the System.Window.Markup namespace documentation.



来源:https://stackoverflow.com/questions/1849214/render-empty-xml-elements-as-parent-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!