我正在使用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的应用程序中对其进行测试)

基本上,如果您在写入end元素之前不添加任何数据,它将为您关闭它。

我还具有以下XmlWriterSettings,如果默认情况下不起作用,则可能是其中之一:
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
wSettings.ConformanceLevel = ConformanceLevel.Fragment;
wSettings.OmitXmlDeclaration = true;
XmlWriter output = XmlWriter.Create(filePathXml, wSettings);

09-25 20:52