繁体   English   中英

指示 XmlWriterSettings 使用自闭合标签

[英]Instruct XmlWriterSettings to use self-closing tags

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

<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 控件,它有节点,每个节点都有一个标记 class MissionNode,它有 ToXml 方法返回包含此 MissionNode 的 XmlNode 转换为 xml

您不需要为此进行任何特殊设置:

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

这将为您提供<element a="1" />的 output(刚刚在我正在为其编写 xml 的应用程序中对其进行了测试)

基本上,如果您在编写结束元素之前不添加任何数据,它只会为您关闭它。

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

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

从外部文件处理 XML,我写了以下 class 来摆脱非空封闭元素。 我的 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;
                })
            );
        }

    }
}

使用正则表达式和递归方法,这很容易:

    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实例,但其所有符合条件(无内容)的完整结束标签现在都已缩短

暂无
暂无

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

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