XmlDocument save File
| The code is as follows |
Copy Code |
|
XmlDocument doc = new XmlDocument ();
Try
{
Doc. Load ("New.xml");
}
Catch
{
XmlTextWriter xtw = new XmlTextWriter ("New.xml", Encoding.UTF8);
New XML file
Xtw. WriteStartDocument ();
Xtw. WriteStartElement ("Gnode");
Gnode root Node
Xtw. WriteStartElement ("myxm1");
Gnode the elements under the root node myxmls
Xtw. WriteEndElement ();
Xtw. WriteEndElement ();
Xtw. WriteEndDocument ();
Xtw. Close ();
Doc. Load ("New.xml");
}
XmlNode xn = doc. DocumentElement;
Root node found
XmlElement XE = Doc. CreateElement ("MYXML2");
Creates an element under the root node and, if it is a property, with XmlAttribute;
Xe. innertext = "hahaha";
Writing a text node to a child node (value)
Xn. AppendChild (XE);
Root node to include it in the
Doc. Save ("New2.xml");
Save files with XmlDocument
}
|
To generate elements of an XML file from the values in the DataSet object of the database
| The code is as follows |
Copy Code |
using (SqlConnection con = new SqlConnection ("server=.;D Atabase=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");
The dataset becomes the root node name in the XML file, or the system names it as NewDataSet
SqlDataAdapter SDA = new SqlDataAdapter ();
Sda. SelectCommand = command;
Sda. Fill (ds, "DATATABLE");
The DataTable is the name of the child node in the generated XML file, or the system names it as a table.
Ds. WriteXml ("Dbxml.xml");
The DataSet method WriteXml writes data to an XML file, that's the word. If you do not save to a file, direct DS. GetXML ()
} |
Using XmlSerializer to convert the property value of a class to an element value of an XML file
| The code is as follows |
Copy Code |
|
[XmlRoot ("Truck")]
----Set as the root element name in XML
Public Truck ()
{ }
[XmlAttribute ("id")]
--------set as a property in XML
public int ID
{
Get{return this._id;}
set {this._id = value;}
}
[XmlElement ("Chepai")]
------Set as an element in the XML (default state)
public string Cheid
{
get {
return This._cheid;
}
set {
This._cheid = value;
}
}
private int _id = 0;
private string _cheid = "";
|
3.2. Create a XmlSerializer instance
The code is as follows:
| The code is as follows |
Copy Code |
|
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--complete serialization of classes
| The code is as follows |
Copy Code |
XmlTextWriter xtw = new XmlTextWriter ("Myxml.xml", Encoding.UTF8);
|
Create an XML file with XmlTextWriter
Ser. Serialize (XTW, TR);
If you only want to show, you can directly ser. Serialize (Console.Out, TR);
}