. Net XML creation 02 (linqToXml), xmllinqtoxml

Source: Internet
Author: User
Tags net xml

. 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>

Related Article

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.