Creation of XML in. NET (linqtoxml)

Source: Internet
Author: User

Linqtoxml comparison is flexible and convenient, it is based on functional programming
The specific use is as follows:
Referencing the assembly using System.Xml.Linq;

1. Create a 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 Node

XDoc. Add (root);//adding child nodes

3. Create child nodes and add attributes

Similar to DOM schema creation

XElement stu= New XElement ("Student");//Create Student node

XAttribute id= New XAttribute ("id", "001");//create a property ID and set the value to "001"

Stu.add (ID);//Add id attribute for Stu node

Chained mode creation

XElement stu= New XElement ("Student", New XAttribute ("id", "001"));

4. Create a child node for student (three Methods of creation)

XElement name = new XElement ("name");

XText xt = new XText ("Zhang San");

  Name. Add (XT);

XElement age = New XElement ("Age");

  Age. Value = "12";

  XElement gender = new XElement ("Gender", "male");

5. Save
XDoc. Save ("Xxx.xml");

Complete chained 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", "page"), New XElement ("Gender", "Male"))). Save ("Xxx.xml");

Build Result:

<?xml version= "1.0" encoding= "gb2312"?>
<root>
<student id= "001" >
<Name> Zhang San </Name>
<Age>12</Age>
<Gender> Men </Gender>
</Student>
</root>

Creation of XML in. NET (linqtoxml)

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.