Force XmlDocument to save empty elements with an explicit closing tag

折月煮酒 提交于 2019-12-06 09:38:26

Here are three ways to force XmlDocument.Save to output a separate end tag for an empty XmlElement instead of an empty, self-closing tag.

Method 1

Insert an empty whitespace node inside the element:

UsersNode.AppendChild(Settings.CreateWhitespace(""));

Here's the output:

<Users FileDirectory="C:\data"></Users>

Method 2

Set the XmlElement.IsEmpty property of the element to false:

((XmlElement)UsersNode).IsEmpty = false;

Note that with this method, the default XML formatting settings will insert a line break between the start tag and the end tag. Here's the output:

<Users FileDirectory="C:\data">
</Users>

Method 3

Derive a custom XmlTextWriter that forwards all WriteEndElement calls to WriteFullEndElement:

public class CustomXmlTextWriter : XmlTextWriter
{
    public CustomXmlTextWriter(string fileName)
        : base(fileName, Encoding.UTF8)
    {
        this.Formatting = Formatting.Indented;
    }

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

Usage:

using (var writer = new CustomXmlTextWriter(Path.Combine(PathName, FileName)))
{
    Settings.Save(writer);
}

This method might require less code overall if you have a lot of empty elements in your document.

As with Method 2, the default XML formatting settings will insert a line break between the start tag and end tag of each empty element.

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