C # generate an XML empty element/empty node wrap solution,
Using DataSet, you can directly output XML and specify whether the Schema is included:
ds.WriteXml(XMLFile,XmlWriteMode.WriteSchema )
However, fields with a Null value will not be output, such:
You may want the result to be as follows:
<a>1</a> <b>2</b> <c></c>
But the result is:
<a>1</a> <b>2</b>
C is not output in XML files. In fact, I think this is more reasonable. Otherwise, how can we distinguish between null and? If you want to Output c, you can only write it by yourself through XmlDocument:
// Initialize an xml instance XmlDocument XmlDoc = new XmlDocument (); XmlNode xmlnode = XmlDoc. createNode (XmlNodeType. xmlDeclaration, "", ""); XmlDoc. appendChild (xmlnode); // create the xml root node XmlElement rootElement = XmlDoc. createElement ("Rows"); // Add the root node to the xml file (AppendChild) XmlDoc. appendChild (rootElement); foreach (DataRow dr in ds. tables [0]. rows) {XmlElement xmlRow = XmlDoc. createElement ("Row"); rootElement. appendChild (xmlRow); foreach (DataColumn col in ds. tables [0]. columns) {XmlElement xmlCol = XmlDoc. createElement (col. columnName); xmlCol. innerText = dr [col]. toString (); xmlRow. appendChild (xmlCol) ;}} XmlDoc. save (file );
The empty node is displayed, but another problem occurs. The empty node is wrapped in a line break as follows:
<a>1</a> <b>2</b> <c> </c>
Although this is also in line with the XML standard, it is easy to read the XML using C #, but for some people with aesthetic cleanliness and already written XML import programs, I always hope to improve it, place the empty element in a row. Some people say that the Formatting of XmlTextWriter is used, that is:
using (XmlTextWriter xtw = new XmlTextWriter(file, null)) { xtw.Formatting = Formatting.None; XmlDoc.Save(xtw); }
But in this way, all content in XML is connected without line breaks, and the readability is worse. In fact, when the value is NULL or "", do not assign a value to InnerText:
if (dr[col].ToString() != null && dr[col].ToString() != "") { xmlCol.InnerText = dr[col].ToString(); }
Output:
<a>1</a> <b>2</b> <c/>