指示 XmlWriterSettings 使用自闭合标记
本文关键字:自闭 XmlWriterSettings 指示 | 更新日期: 2023-09-27 18:30:23
我正在使用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 方法,该方法返回包含此 MissionNode 转换为 xml 的 XmlNode
您不需要任何特殊设置:
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);
处理来自外部文件的 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;
})
);
}
}
}
使用正则表达式和递归方法,很容易完成:
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
的实例,但其所有符合条件的(没有内容)完整结束标签现在都缩短了