. Net XML creation 02 (linqToXml), xmllinqtoxml
LinqToXml is flexible and convenient. It is based on functional programming.
The specific usage is as follows:
Reference assembly using System. Xml. Linq;
1. Create an XDocument and set the Document Header
XDocument XDoc = new XDocument ();
XDoc. Declaration = new XDeclaration ("1, 0", "gb2312", null );
2. Create the root node element XElement
XElement root = new XElement ("root"); // create a node
XDoc. Add (root); // Add a subnode
3. Create a subnode and add attributes
// Create in dom-like Mode
XElement stu = new XElement ("Student"); // create a Student Node
XAttribute id = new XAttribute ("id", "001"); // create an attribute id and set it to "001"
Stu. add (id); // add the id attribute for the stu Node
// Create a chain mode
XElement stu = new XElement ("Student", new XAttribute ("id", "001 "));
4. Create a subnode for Student (three methods)
XElement name = new XElement ("Name ");
XText xt = new XText ("zhangsan ");
Name. Add (xt );
XElement age = new XElement ("Age ");
Age. Value = "12 ";
XElement gender = new XElement ("Gender", "male ");
5. Save
XDoc. Save ("xxx. xml ");
Complete Chain Creation
New XDocument (new XDeclaration ("1.0", "gb2312", null), new XElement ("root", new XElement ("Student", new XAttribute ("id ", "001"), new XElement ("Name", "Zhang San"), new XElement ("Age", "12"), new XElement ("Gender ", "male ")))). save ("xxx. xml ");
Result:
<? Xml version = "1.0" encoding = "gb2312"?>
<Root>
<Student id = "001">
<Name> Zhang San </Name>
<Age> 12 </Age>
<Gender> male </Gender>
</Student>
</Root>