C # Three ways to generate XML

Source: Internet
Author: User

 

For the sake of comprehensiveness, XML is saved to the file here. There are three ways to generate XML: 1. I think it is the most primitive and basic one: Use XmlDocument to write nodes to an XML file, and then use XmlDocument to save the file. First, load the XML file to be written, but if there is no, create a new file. During the creation process, write code is required;

XmlDocument doc = new XmlDocument ();
Try
{
Doc. Load ("new. xml ");
}
Catch
{
XmlTextWriter xtw = new XmlTextWriter ("new. xml", Encoding. UTF8 );
// Create an XML file
Xtw. WriteStartDocument ();
Xtw. WriteStartElement ("gnode ");
// Gnode Root Node
Xtw. WriteStartElement ("myxm1 ");
// The element myxmls under the root node of gnode
Xtw. WriteEndElement ();
Xtw. WriteEndElement ();
Xtw. WriteEndDocument ();
Xtw. Close ();
Doc. Load ("new. xml ");
}
XmlNode xn = doc. DocumentElement;
// Find the root node
XmlElement xe = doc. CreateElement ("myxml2 ");
// Create an element under the root node. If it is an attribute, use XmlAttribute;
Xe. InnerText = "hahaha ";
// Write a text node (value) to the subnode)
Xn. AppendChild (xe );
// Add the root node
Doc. Save ("new2.xml ");
// Use XmlDocument to save the object
}

Note: When creating a root node, WriteStartElement can only be nested, that is, there can only be one root node.

2. Apply the value in the DataSet object of the database to Generate Elements of the XML file;

Using (SqlConnection con = new SqlConnection ("Server =.; DataBase = HGSTUDY; uid = sa; pwd = yao "))
{
Con. Open ();
SqlCommand command = new SqlCommand ("select * from GL_STUDY", con );
Command. CommandType = CommandType. Text;
DataSet ds = new DataSet ("DATASET ");
// DATASET will be the root node name in the XML file. Otherwise, the system will name it NewDataSet.
SqlDataAdapter sda = new SqlDataAdapter ();
Sda. SelectCommand = command;
Sda. Fill (ds, "DATATABLE ");
// DATATABLE is the name of the child node in the generated XML file. Otherwise, the system will name it Table.
Ds. WriteXml ("dbxml. xml ");
// The DataSet method WriteXml writes data to the XML file, which is such a sentence. If the file is not saved, ds. GetXML () is used directly ()
}

3. XmlSerializer is used to convert the class property value to the element value of the XML file. Use a string as the xmlAttribute or xmlElement in an XML document. [Its elements or attributes are set by the class definition (serialized in xml)]

Using System; System. xml. Serialization;

3. 1. initialize a class and set the attribute value.

[XmlRoot ("Truck")]
// ---- Set the name of the root element in XML
Public Truck ()
{}
[XmlAttribute ("id")]
// -------- Set as an attribute in xml
Public int ID
{
Get {return this. _ id ;}
Set {this. _ id = value ;}
}
[XmlElement ("chepai")]
// ------ Set as an element in XML (default state)
Public string cheID
{
Get {
Return this. _ cheID;
}
Set {
This. _ cheID = value;
}
}
Private int _ id = 0;
Private string _ cheID = "";

3. 2. Create an XmlSerializer instance

Class XXX {
XmlSerializer ser = new XmlSerializer (Type. GetType ("forxml. truck "));
Truck tr = new Truck ();
Tr. ID = 1;
Tr. cheID = "Gan A T34923 ";
}

3.3.Serialize Method -- serializing classes

XmlTextWriter xtw = new XmlTextWriter ("myxml. xml", Encoding. UTF8 );

Create an XML file with XmlTextWriter

Ser. Serialize (xtw, tr );

If you only want to display, you can directly ser. Serialize (Console. Out, tr );

}

 

In my personal summary, there are only three methods described here. It will be good after flexible application. You can directly input them, or use databases or classes. It can be used to generate XML in C.

For the sake of comprehensiveness, XML is saved to the file here. There are three ways to generate XML: 1. I think it is the most primitive and basic one: Use XmlDocument to write nodes to an XML file, and then use XmlDocument to save the file. First, load the XML file to be written, but if there is no, create a new file. During the creation process, write code is required;

XmlDocument doc = new XmlDocument ();
Try
{
Doc. Load ("new. xml ");
}
Catch
{
XmlTextWriter xtw = new XmlTextWriter ("new. xml", Encoding. UTF8 );
// Create an XML file
Xtw. WriteStartDocument ();
Xtw. WriteStartElement ("gnode ");
// Gnode Root Node
Xtw. WriteStartElement ("myxm1 ");
// The element myxmls under the root node of gnode
Xtw. WriteEndElement ();
Xtw. WriteEndElement ();
Xtw. WriteEndDocument ();
Xtw. Close ();
Doc. Load ("new. xml ");
}
XmlNode xn = doc. DocumentElement;
// Find the root node
XmlElement xe = doc. CreateElement ("myxml2 ");
// Create an element under the root node. If it is an attribute, use XmlAttribute;
Xe. InnerText = "hahaha ";
// Write a text node (value) to the subnode)
Xn. AppendChild (xe );
// Add the root node
Doc. Save ("new2.xml ");
// Use XmlDocument to save the object
}

Note: When creating a root node, WriteStartElement can only be nested, that is, there can only be one root node.

2. Apply the value in the DataSet object of the database to Generate Elements of the XML file;

Using (SqlConnection con = new SqlConnection ("Server =.; DataBase = HGSTUDY; uid = sa; pwd = yao "))
{
Con. Open ();
SqlCommand command = new SqlCommand ("select * from GL_STUDY", con );
Command. CommandType = CommandType. Text;
DataSet ds = new DataSet ("DATASET ");
// DATASET will be the root node name in the XML file. Otherwise, the system will name it NewDataSet.
SqlDataAdapter sda = new SqlDataAdapter ();
Sda. SelectCommand = command;
Sda. Fill (ds, "DATATABLE ");
// DATATABLE is the name of the child node in the generated XML file. Otherwise, the system will name it Table.
Ds. WriteXml ("dbxml. xml ");
// The DataSet method WriteXml writes data to the XML file, which is such a sentence. If the file is not saved, ds. GetXML () is used directly ()
}

3. XmlSerializer is used to convert the class property value to the element value of the XML file. Use a string as the xmlAttribute or xmlElement in an XML document. [Its elements or attributes are set by the class definition (serialized in xml)]

Using System; System. xml. Serialization;

3. 1. initialize a class and set the attribute value.

[XmlRoot ("Truck")]
// ---- Set the name of the root element in XML
Public Truck ()
{}
[XmlAttribute ("id")]
// -------- Set as an attribute in xml
Public int ID
{
Get {return this. _ id ;}
Set {this. _ id = value ;}
}
[XmlElement ("chepai")]
// ------ Set as an element in XML (default state)
Public string cheID
{
Get {
Return this. _ cheID;
}
Set {
This. _ cheID = value;
}
}
Private int _ id = 0;
Private string _ cheID = "";

3. 2. Create an XmlSerializer instance

Class XXX {
XmlSerializer ser = new XmlSerializer (Type. GetType ("forxml. truck "));
Truck tr = new Truck ();
Tr. ID = 1;
Tr. cheID = "Gan A T34923 ";
}

3.3.Serialize Method -- serializing classes

XmlTextWriter xtw = new XmlTextWriter ("myxml. xml", Encoding. UTF8 );

Create an XML file with XmlTextWriter

Ser. Serialize (xtw, tr );

If you only want to display, you can directly ser. Serialize (Console. Out, tr );

}

 

In my personal summary, there are only three methods described here. It will be good after flexible application. You can directly input them, or use databases or classes. It can be used to generate XML in C.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.