The dataset can be used to output XML directly and to specify whether it has a schema:
Ds. WRITEXML (Xmlfile,xmlwritemode.writeschema )
However, this will not output a null-value field, such as:
You might want the result to look like this:
<a>1</a> <b>2</b>
But the result is:
<a>1</a> <b>2</b>
c there is no output in the XML file, in fact I think it is more reasonable, otherwise, how to distinguish between null and ""? If you want to output C, that can only be written by XmlDocument yourself:
//initializing an XML instanceXmlDocument xmldoc =NewXmlDocument (); XmlNode XmlNode= Xmldoc.createnode (Xmlnodetype.xmldeclaration,"",""); Xmldoc.appendchild (XmlNode); //Create the root node of the XMLXmlElement rootelement = xmldoc.createelement ("Rows"); //Adding a root node to an XML file (appendchild)Xmldoc.appendchild (rootelement); foreach(DataRow DrinchDs. tables[0]. Rows) {XmlElement Xmlrow= Xmldoc.createelement ("Row"); Rootelement.appendchild (Xmlrow); foreach(DataColumn ColinchDs. tables[0]. Columns) {XmlElement Xmlcol=Xmldoc.createelement (Col. ColumnName); Xmlcol.innertext=Dr[col]. ToString (); Xmlrow.appendchild (Xmlcol); }} xmldoc.save (file);
The empty node shows up, but another problem arises, and the empty node wraps, and it becomes this:
<a>1</a> <b>2</b> <c> </c>
Although this also conforms to the XML standard, it is easy to read the XML using C #, but for some people who have an aesthetic sense of cleanliness and a well-written XML importer, they always want to improve and put empty elements in one line. Some say that using XmlTextWriter's formatting, namely:
using New NULL ) ) { = formatting.none; Xmldoc.save (XTW); }
But in this way, all the content in XML is not wrapped together, and the readability is even worse. Do not assign a value to innertext when the value is actually null or "":
if NULL "" ) { = Dr[col]. ToString (); }
Output:
<a>1</a> <b>2</b> <c/>
C # Generate XML empty element/empty node wrap solution