Istrebitel Istrebitel - 5 months ago 87
C# Question

Instruct XmlWriterSettings to use self-closing tags

I'm using XmlWriterSettings to write Xml to file. I have elements with only attributes, no children. I want them to output as:

<element a="1" />

instead of

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

Can i do it with XmlWriterSettings?


Code is as follows:

private void Mission_Save(string fileName)
StreamWriter streamWriter = new StreamWriter(fileName, false);

_MissionFilePath = fileName;

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

xDoc = new XmlDocument();

foreach (string item in _MissionCommentsBefore)

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

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

foreach (string item in _MissionCommentsAfter)

//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))

return sb.ToString();

private void Mission_ToXml_private_RecursivelyOut(XmlNode root, XmlDocument xDoc, TreeNode tNode)
foreach (TreeNode node in tNode.Nodes)
Mission_ToXml_private_RecursivelyOut(root, xDoc, node);

here _FM_tve_Mission is a TreeView control which has nodes, each of the nodes has a tag of class MissionNode, which has ToXml method that returns XmlNode containing this MissionNode converted to xml


You dont need any special settings for that:

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

That will give you an output of <element a="1" /> (Just tested it in an application I am working on writing xml for)

Basically if you dont add any data before you write the end element it will just close it off for you.

I also have the following XmlWriterSettings it may be one of these if it isnt working by default:

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