XML class for LINQ operations

Source: Internet
Author: User
Tags processing instruction
1. LINQ to XML class

The following code demonstrates how to use LINQ to XML to quickly create an XML file:

public static void CreateDocument(){    string path = @"d:\website";    XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),                                   new XElement("Root", "root"));    xdoc.Save(path);}

 

Run this example to get an XML file with the following content:

<?xml version="1.0" encoding="utf-8" standalone="yes"?><Root>root</Root>
2. xelement class

The xelement class is one of the basic classes in LINQ to XML. It represents an XML element. You can use this class to create elements, change element content, add, change, or delete child elements, add attributes to elements, or serialize Element Content in text format. It can also interoperate with other classes in system. XML (such as xmlreader, xmlwriter, and compiledtransform.

There are many ways to create an XML document using LINQ to XML. The specific method should be based on actual needs. The simplest and most common way to create an XML document is to use the xelement class. The following code demonstrates how to use the xelement class to create an XML document:

public static void CreateCategories(){    string path = @"d:\website";    XElement root = new XElement("Categories",        new XElement("Category",            new XElement("CategoryID", Guid.NewGuid()),            new XElement("CategoryName", "Beverages")            ),        new XElement("Category",            new XElement("CategoryID", Guid.NewGuid()),            new XElement("CategoryName", "Condiments")            ),        new XElement("Category",            new XElement("CategoryID", Guid.NewGuid()),            new XElement("CategoryName", "Confections")            )       );    root.Save(path);}

 

Run this example to get an XML file with the following content:

<?xml version="1.0" encoding="utf-8"?><Categories>  <Category>    <CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>    <CategoryName>Beverages</CategoryName>  </Category>  <Category>    <CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>    <CategoryName>Condiments</CategoryName>  </Category>  <Category>    <CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>    <CategoryName>Confections</CategoryName>  </Category></Categories>

 

The xelement class contains many methods that make it easy to process XML. For more information about these methods, see msdn.

The SAVE, createreader, tostring, and writeto methods are commonly used in three methods:

3. xattribute class

The xattribute class is used to process attributes of an element. An attribute is a "name-value" pair associated with an element. Each element cannot contain attributes with duplicate names. The xattribute class is similar to the operation using the xelement class. The following example shows how to add an attribute to the XML tree:

public static XElement CreateCategoriesByXAttribute(){    XElement root = new XElement("Categories",        new XElement("Category",            new XAttribute("CategoryID", Guid.NewGuid()),            new XElement("CategoryName", "Beverages")            ),        new XElement("Category",            new XAttribute("CategoryID", Guid.NewGuid()),            new XElement("CategoryName", "Condiments")            ),        new XElement("Category",            new XAttribute("CategoryID", Guid.NewGuid()),            new XElement("CategoryName", "Confections")            )       );    root.Save(path);    return root;}

 

Run this example to get an XML file with the following content:

 

<?xml version="1.0" encoding="utf-8"?><Categories>  <Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570">    <CategoryName>Beverages</CategoryName>  </Category>  <Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb">    <CategoryName>Condiments</CategoryName>  </Category>  <Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76">    <CategoryName>Confections</CategoryName>  </Category></Categories>

There are few methods for the xattribute class. Three common methods are:

The following example uses remove to delete the categoryid attribute of the first element:

public static void RemoveAttribute(){    XElement xdoc = CreateCategoriesByXAttribute();    XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID");    xattr.Remove();    xdoc.Save(path);}

 

Run this example to get an XML file with the following content:

 

<?xml version="1.0" encoding="utf-8"?><Categories>  <Category>    <CategoryName>Beverages</CategoryName>  </Category>  <Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346">    <CategoryName>Condiments</CategoryName>  </Category>  <Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712">    <CategoryName>Confections</CategoryName>  </Category></Categories>

Try the following methods to delete attributes:

 

public static void RemoveAttributeByDoc(){    XElement xdoc = CreateCategoriesByXAttribute();    XAttribute xattr = xdoc.Attribute("CategoryID");    xattr.Remove();    xdoc.Save(path);}

Running this example throws an empty reference exception because the element categories does not have a property called categoryid.

4. xdocument class

The xdocument class provides methods for processing XML documents, including declarations, comments, and processing instructions. An xdocument object can contain the following content:

The following example creates a simple XML document that contains several elements and an attribute, as well as a processing instruction and some comments:

public static void CreateXDocument()      {          XDocument xdoc = new XDocument(                  new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"),                  new XComment("some comments"),                  new XElement("Root",                          new XElement("Employees",                                  new XElement("Employee",                                          new XAttribute("id", "1"),                                          new XElement("Name", "Scott Klein"),                                          new XElement("Title", "Geek"),                                          new XElement("HireDate", "02/05/2007"),                                          new XElement("Gender", "M")                                      )                              )                      ),                  new XComment("more comments")              );          xdoc.Save(path);      }

 

Run this example to get an XML file with the following content:

 

<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet title='EmpInfo'?><!--some comments--><Root>  <Employees>    <Employee id="1">      <Name>Scott Klein</Name>      <Title>Geek</Title>      <HireDate>02/05/2007</HireDate>      <Gender>M</Gender>    </Employee>  </Employees></Root><!--more comments-->

The xdocument class contains multiple methods identical to the xelement class. For details, see msdn. It should be noted that most of the functions of processing nodes and elements can be obtained through xelement, only when the processing capability at the document level is absolutely required, as well as the need to access comments, process commands and declarations, to use the xdocument class.

After creating an XML document, you can use the nodesafterself method to return all the same-level elements after the specified xelement. Note that this method only includes the same-level elements in the returned set, not the child. This method uses delayed execution. The following code demonstrates this process:

Public static void nodesafterself () {xelement root = new xelement ("categories", new xelement ("category", new xelement ("categoryid", guid. newguid (), new xelement ("categoryname", "food"), new xelement ("Description", "something you can eat"); foreach (VAR item in root. element ("category "). element ("categoryid "). nodesafterself () {console. writeline (item as xelement ). value );}}

 

2. Programming Concepts of LINQ to XML

This section describes the concepts related to the programming of LINQ to XML, such as how to load XML, create new XML, manipulate XML Information, and traverse XML documents.

1. Load existing XML

You can use LINQ to XML to load XML from multiple data sources, such as strings, xmlreader, textreader, or files.

The following example demonstrates how to load XML from a file:

public static void LoadFromFile(){    XElement root = XElement.Load(path);    Console.WriteLine(root.ToString());}

 

You can also use the parse method to load XML from a string:

    public static void LoadFromString()    {        XElement root = XElement.Parse(@"    <Categories>      <Category>        <CategoryID>1</CategoryID>        <CategoryName>Beverages</CategoryName>        <Description>Soft drinks, coffees, teas, beers, and ales</Description>      </Category>    </Categories>");        Console.WriteLine(root.ToString());    }

 

2. Save XML

In the previous example, the save method of the xelement object was called multiple times to save the XML document.

3. Create XML

In the previous example, the xelement object constructor was called multiple times to create an XML document. It should be noted that code indentation occurs when you create an XML document using LINQ to XML, which greatly enhances the readability of the Code.

4. Traverse XML

It is quite easy to traverse XML in the XML tree using LINQ to XML. You only need to use the methods provided in the xelement and xattribute classes. The elements and element methods provide a way to locate one or more elements. The following example shows how to traverse the XML tree and obtain the specified element:

public static void Enum(){    XElement root = new XElement("Categories");    using (NorthwindDataContext db = new NorthwindDataContext())    {        root.Add(                db.Categories                .Select                (                    c => new XElement                    (                        "Category"                        , new XElement("CategoryName", c.CategoryName)                    )                )            );    }    foreach (var item in root.Elements("Category"))    {        Console.WriteLine(item.Element("CategoryName").Value);    }}

The result of running the above Code is:

Is it easy? The nodes (), elements (), element (name), and elements (name) methods provide basic functions for the navigation of the XML tree.

5. manipulate XML

An important feature of LINQ to XML is the ability to easily modify the XML tree, such as adding, deleting, updating, and copying the content of XML documents.

I. insert

You can easily add content to the XML tree using the insert method of the xnode class:

In the following example, add a new node to the existing XML using the addafterself method:

public static void AddAfterSelf(){    XElement root = XElement.Parse(@"        <Categories>          <Category>            <CategoryID>1</CategoryID>            <CategoryName>Beverages</CategoryName>            <Description>Soft drinks, coffees, teas, beers, and ales</Description>          </Category>        </Categories>    ");    XElement xele = root.Element("Category").Element("CategoryName");    xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));    root.Save(path);}

 

Run this example to get an XML file with the following content:

 

<?xml version="1.0" encoding="utf-8"?><Categories>  <Category>    <CategoryID>1</CategoryID>    <CategoryName>Beverages</CategoryName>    <AddDate>2010-01-31T03:08:51.813736+08:00</AddDate>    <Description>Soft drinks, coffees, teas, beers, and ales</Description>  </Category></Categories>

 

You can use the addbeforeself method to add an element to a specified node.

Ii. Update

You can use the following methods to update XML content in LINQ to XML:

In the following example, the replacewith and setelementvalue methods are used to update XML:

public static void Update(){    XElement root = XElement.Parse(@"                                   <Categories>                                      <Category>                                        <CategoryID>1</CategoryID>                                        <CategoryName>Beverages</CategoryName>                                        <Description>Soft drinks, coffees, teas, beers, and ales</Description>                                      </Category>                                    </Categories>                                  ");    root.Element("Category").Element("CategoryID").ReplaceWith(new XElement("ID", "2"));    root.Element("Category").SetElementValue("CategoryName", "test data");    root.Save(path);}

Run this example to get an XML file with the following content:

<?xml version="1.0" encoding="utf-8"?><Categories>  <Category>    <ID>2</ID>    <CategoryName>test data</CategoryName>    <Description>Soft drinks, coffees, teas, beers, and ales</Description>  </Category></Categories>

 

Iii. Delete

You can use the remove (xelement) and removeall methods to delete XML files.

In the following example, the removeall method is used:

}  public static void Remove()  {      string path = @"d:\";      XElement root = XElement.Parse(@"                                  <Categories>                                    <Category>                                      <CategoryID>1</CategoryID>                                      <CategoryName>Beverages</CategoryName>                                      <Description>Soft drinks, coffees, teas, beers, and ales</Description>                                    </Category>                                  </Categories>                                ");      root.RemoveAll();      root.Save(path);  }

 

Run this example to get an XML file with the following content:

<?xml version="1.0" encoding="utf-8"?><Categories />

In the following example, the remove method is used to delete the description element of XML:

public static void Remove(){    XElement root = XElement.Parse(@"                                <Categories>                                  <Category>                                    <CategoryID>1</CategoryID>                                    <CategoryName>Beverages</CategoryName>                                    <Description>Soft drinks, coffees, teas, beers, and ales</Description>                                  </Category>                                </Categories>                                ");    root.Element("Category").Element("Description").Remove();    root.Save(path);}

 

Run this example to get an XML file with the following content:

<?xml version="1.0" encoding="utf-8"?><Categories>  <Category>    <CategoryID>1</CategoryID>    <CategoryName>Beverages</CategoryName>  </Category></Categories>
6. process attributes

I. Add

The addition of attributes in LINQ to XML is similar to that in addition to the element division. You can use constructors or the add method to add attributes:

public static void AddAttribute(){    XElement root = new XElement("Categories",        new XElement("Category",            new XAttribute("CategoryID", "1"),            new XElement("CategoryName", "Beverages"),            new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")        )    );    root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString()));    root.Save(path);}

 

Run this example to get an XML file with the following content:

<?xml version="1.0" encoding="utf-8"?><Categories>  <Category CategoryID="1" AddDate="2010-01-31">    <CategoryName>Beverages</CategoryName>    <Description>Soft drinks, coffees, teas, beers, and ales</Description>  </Category></Categories>

 

Ii. Search

You can use the attribute (name) method to retrieve attributes:

public static void SelectAttribute(){    XElement root = new XElement("Categories",        new XElement("Category",            new XAttribute("CategoryID", "1"),            new XElement("CategoryName", "Beverages"),            new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")        )    );    XAttribute xattr = root.Element("Category").Attribute("CategoryID");    Console.WriteLine(xattr.Name);    Console.WriteLine(xattr.Value);}

 

The running result of the above Code is:

Categoryid

1

Summary

 

This topic describes the basics of programming to XML, namely, system. XML. there are multiple LINQ to XML classes in the LINQ namespace. These classes are all supported classes of LINQ to XML, which make it easier to process XML than other XML tools. This article focuses on xelement, xattribute, and xdocument.

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.