Istrebitel Istrebitel - 1 month ago 19
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?

EDIT:

Code is as follows:

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);
}


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

Answer

You dont need any special settings for that:

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

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