指示XmlWriterSettings使用自闭标签

时间:2012-04-06 18:55:20

标签: c# xml xmlwriter

我正在使用XmlWriterSettings将Xml写入文件。我的元素只有属性,没有孩子。我希望它们输出为:

<element a="1" /> 

而不是

<element a="1"></element>

我可以使用XmlWriterSettings吗?

编辑:

代码如下:

private void Mission_Save(string fileName)
    {
        StreamWriter streamWriter = new StreamWriter(fileName, false);
        streamWriter.Write(Mission_ToXml());
        streamWriter.Close();
        streamWriter.Dispose();

        _MissionFilePath = fileName;
    }

private string Mission_ToXml()
    {
        XmlDocument xDoc;
        XmlElement root;
        XmlAttribute xAtt;

        xDoc = new XmlDocument();

        foreach (string item in _MissionCommentsBefore)
            xDoc.AppendChild(xDoc.CreateComment(item));

        root = xDoc.CreateElement("mission_data");
        xAtt = xDoc.CreateAttribute("version");
        xAtt.Value = "1.61";
        root.Attributes.Append(xAtt); 
        xDoc.AppendChild(root);

        //Out the xml's!
        foreach (TreeNode node in _FM_tve_Mission.Nodes)
            Mission_ToXml_private_RecursivelyOut(root, xDoc, node);

        foreach (string item in _MissionCommentsAfter)
            xDoc.AppendChild(xDoc.CreateComment(item));


        //Make this look good
        StringBuilder sb = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings();

        settings.Indent = true;
        settings.IndentChars = "  ";
        settings.NewLineChars = "\r\n";
        settings.NewLineHandling = NewLineHandling.Replace;
        settings.OmitXmlDeclaration = true;
        using (XmlWriter writer = XmlWriter.Create(sb, settings))
        {
            xDoc.Save(writer);
        }

        return sb.ToString();
    }

private void Mission_ToXml_private_RecursivelyOut(XmlNode root, XmlDocument xDoc, TreeNode tNode)
    {
        root.AppendChild(((MissionNode)tNode.Tag).ToXml(xDoc));
        foreach (TreeNode node in tNode.Nodes)
            Mission_ToXml_private_RecursivelyOut(root, xDoc, node);
    }

这里_FM_tve_Mission是一个TreeView控件,它有节点,每个节点都有一个类MissionNode的标签,它有ToXml方法,返回包含转换为xml的MissionNode的XmlNode

3 个答案:

答案 0 :(得分:8)

您不需要任何特殊设置:

XmlWriter output = XmlWriter.Create(filepath);
 output.writeStartElement("element");
 output.writeAttributeString("a", "1");
 output.writeEndElement();

这将为您提供<element a="1" />的输出(刚刚在我正在编写xml的应用程序中测试过它)

基本上,如果你在编写结束元素之前没有添加任何数据,它将为你关闭它。

我还有以下XmlWriterSettings如果它默认不起作用,它可能是其中之一:

XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
wSettings.ConformanceLevel = ConformanceLevel.Fragment;
wSettings.OmitXmlDeclaration = true;
XmlWriter output = XmlWriter.Create(filePathXml, wSettings);

答案 1 :(得分:1)

从外部文件处理XML,我写了下面的类来摆脱非空的封闭元素。我的XML现在有自闭标签。

using System.Linq;
using System.Xml.Linq;

namespace XmlBeautifier
{
    public class XmlBeautifier
    {
        public static string BeautifyXml(string outerXml)
        {
            var _elementOriginalXml = XElement.Parse(outerXml);
            var _beautifiedXml = CloneElement(_elementOriginalXml);
            return _beautifiedXml.ToString();
        }

        public static XElement CloneElement(XElement element)
        {
            // http://blogs.msdn.com/b/ericwhite/archive/2009/07/08/empty-elements-and-self-closing-tags.aspx
            return new XElement(element.Name,
                element.Attributes(),
                element.Nodes().Select(n =>
                {
                    XElement e = n as XElement;
                    if (e != null)
                        return CloneElement(e);
                    return n;
                })
            );
        }

    }
}

答案 2 :(得分:0)

使用Regex和递归方法,这很容易:

    using System.Xml.Linq;
    public static class Xml
    {
        /// <summary>
        /// Recursive method to shorten all xml end tags starting from a given element, and running through all sub elements 
        /// </summary>
        /// <param name="elem">Starting point element</param>
        public static void ToShortEndTags(this XElement elem)
        {
            if (elem == null) return;

            if (elem.HasElements)
            {
                foreach (var item in elem.Elements()) ToShortEndTags(item);
                return;
            }

            var reduced = Regex.Replace(elem.ToString(), ">[\\s\\n\\r]*</\\w+>", "/>");

            elem.ReplaceWith(XElement.Parse(reduced));
        }
    }

要使用它,请键入以下内容:

    var path = @"C:\SomeFile.xml";
    var xdoc = XDocument.Load(path).Root.ToShortEndTags();

xdoc现在是XDocument从指定路径加载的实例,但其所有符合条件的(没有内容)完整结束标记现在已缩短