Linq (3) XML operations

Source: Internet
Author: User
1. Use Linq to create an XML

// Create dummy XML to work

Var root = new XElement ("parent ",

From I in new int [] {1, 2, 3, 4, 5, 6}

Select new XElement ("child ",

New XAttribute ("number", I )));

This will create XML like,

<? Xmlversion = "1.0" encoding = "UTF-8"?>

<Parent>

<Childnumber = "1"/>

<Childnumber = "2"/>

<Childnumber = "3"/>

<Childnumber = "4"/>

<Childnumber = "5"/>

<Childnumber = "6"/>

</Parent>

2. query and add an Xml Node

// Get the element (child3)

XElement child3 = root. Descendants ("child"). First (

El => (int) el. Attribute ("number") = 3 );

// Add element before the child3

Child3.AddBeforeSelf (new XElement ("child25 "));

// Add sub-element to the child3

Child3.Add (new XElement ("grandchild "));

// Add element after the child3

Child3.AddAfterSelf (new XElement ("child35 "));

// Add attribute to the child3

Child3.Add (new XAttribute ("attr", "something "));

// Change the existing attribute

Child3.SetAttributeValue ("number", 100 );

After all these activities you will get the following output,

<? Xmlversion = "1.0" encoding = "UTF-8"?>

<Parent>

<Childnumber = "1"/>

<Childnumber = "2"/>

<Child25/>

<Childnumber = "100" attr = "something">

<Grandchild/>

</Child>

<Child35/>

<Childnumber = "4"/>

<Childnumber = "5"/>

<Childnumber = "6"/>

</Parent>

3. delete an Xml Node
Child3.Remove ();

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.