First, LINQ to XML programming Basics
1. LINQ to XML classes
The System.Xml.Linq namespace contains 19 classes, and the following table lists their names and their descriptions:
Class |
Describe |
XAttribute |
Represents an XML attribute |
Xcdata |
Represents a CDATA text node |
Xcomment |
Represents an XML annotation |
XContainer |
Abstract base class for all nodes that may have child nodes |
Xdeclaration |
Represents an XML declaration |
XDocument |
Represents an XML document |
Xdocumenttype |
Represents an XML document type definition (DTD) |
XElement |
Represents an XML element |
XName |
Represents the name of an XML element or attribute |
XNamespace |
Represents an XML namespace |
XNode |
An abstract class that represents the nodes of an XML tree |
Xnodedocumentordercomparer |
Provides the ability to compare the document order of a node |
Xnodeequalitycomparer |
Provides functionality to compare whether a node's values are equal |
Xobject |
Abstract base classes for XNode and XAttribute |
Xobjectchange |
Xobject Event type When an event is raised |
Xobjectchangeeventargs |
Providing data for changing and Changed events |
Xprocessinginstruction |
Represents an XML processing instruction |
XText |
Represents a text node |
The following code demonstrates how to quickly create an XML using LINQ to XML:
Copy Code code as follows:
public static void CreateDocument ()
{
XDocument Xdoc = new XDocument
(
New Xdeclaration ("1.0", "Utf-8", "yes"),
New XElement ("root", "root")
);
Xdoc. Save (path);
}
Running the example will get an XML file with the following contents:
<?xml version= "1.0" encoding= "Utf-8" standalone= "yes"?>
<Root>root</Root>
We can see that Microsoft has put a lot of effort into LINQ, which makes us feel comfortable when we are programming. The following is a detailed description of the top three classes used to process xml: XElement, XAttribute, and XDocument. If you master these classes, you'll feel comfortable using LINQ to XML.
2, XElement class
The XElement class is one of the underlying 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. You can also interoperate with other classes in the System.Xml, such as XmlReader, XmlWriter, and XslCompiledTransform.
There are a number of ways to create XML documents using LINQ to XML, depending on the actual needs of the method used. 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:
Copy Code code as follows:
public static void Createcategories ()
{
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);
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?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 powerful thing about LINQ to XML is that it can get a data source using LINQ to SQL or LINQ to object, and then populate the XML tree. The following example reads the data in the categories, Products table from the Northwind database to create an XML file that contains product categories and all products under each category:
Copy Code code as follows:
public static void Createcategoriesfromdatabase ()
{
using (NorthwindDataContext db = new NorthwindDataContext ())
{
XElement root = New XElement ("Categories",
Db. Categories
. Select
(
C => New XElement
(
"Category"
, New XElement ("CategoryID", C.categoryid)
, New XElement ("CategoryName", C.categoryname)
, New XElement
(
"Products"
, c.products
. Select
(
P => New XElement
(
"Product"
, New XElement ("ProductName", P.productname)
)
)
. Take (2)
)
)
)
. Take (3)
);
Root. Save (path);
}
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Products>
<Product>
<ProductName>Chai</ProductName>
</Product>
<Product>
<ProductName>Chang</ProductName>
</Product>
</Products>
</Category>
<Category>
<CategoryID>2</CategoryID>
<CategoryName>Condiments</CategoryName>
<Products>
<Product>
<productname>aniseed syrup</productname>
</Product>
<Product>
<productname>chef Anton ' s Cajun seasoning</productname>
</Product>
</Products>
</Category>
<Category>
<CategoryID>3</CategoryID>
<CategoryName>Confections</CategoryName>
<Products>
<Product>
<ProductName>Pavlova</ProductName>
</Product>
<Product>
<productname>teatime Chocolate biscuits</productname>
</Product>
</Products>
</Category>
</Categories>
The XElement class contains a number of methods that make it easy to process XML. Refer to MSDN for these methods.
Among them, the Save, Createreader, ToString, and WriteTo methods are the more commonly used three methods:
Method |
Parameters |
return value |
Describe |
Createreader |
No |
System.Xml.XmlReader |
Create the XmlReader for this node |
Save |
System.String |
void |
Serializing this element as a file |
System.IO.TextWriter |
void |
Serializes this element to TextWriter |
System.Xml.XmlWriter |
void |
Serializes this element to XmlWriter |
System.String, System.Xml.Linq.SaveOptions |
void |
Serializes this element to a file and optionally disables formatting |
System.IO.TextWriter, System.Xml.Linq.SaveOptions |
void |
Serializes this element to TextWriter and optionally disables formatting |
WriteTo |
System.Xml.XmlWriter |
void |
Writes this element to the XmlWriter |
Tostring |
No |
System.String |
Returns the indent XML for this node |
System.Xml.Linq.SaveOptions |
System.String |
Returns the XML for this node and optionally disables formatting |
There are many applications that use XmlReader as a data source, and it's easy to support using XElement.
3, XAttribute class
The XAttribute class is used to handle the attributes of an element, which is a "name-value" pair associated with an element, and cannot have attributes with duplicate names in each element. Using the XAttribute class is very similar to using the XElement class, the following example shows how to add an attribute to an XML tree when it is created:
Copy Code code as follows:
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;
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?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 fewer methods for XAttribute classes, and the three commonly used are:
Method |
Describe |
Addannotation |
Add annotations to this property |
Remove |
Delete this property |
SetValue |
Set the value of this property |
The following example uses remove to remove the CategoryID property of the first element:
Copy Code code as follows:
public static void RemoveAttribute ()
{
XElement Xdoc = Createcategoriesbyxattribute ();
XAttribute xattr = Xdoc. Element ("Category"). Attribute ("CategoryID");
Xattr. Remove ();
Xdoc. Save (path);
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?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>
As an attempt, try the following methods for deleting a property:
Copy Code code as follows:
public static void Removeattributebydoc ()
{
XElement Xdoc = Createcategoriesbyxattribute ();
XAttribute xattr = Xdoc. Attribute ("CategoryID");
Xattr. Remove ();
Xdoc. Save (path);
}
Running the example throws a null reference exception because the element categories does not have a property called CategoryID.
4, XDocument Class
The XDocument class provides methods for working with XML documents, including declarations, comments, and processing instructions. A XDocument object can contain the following contents:
Object |
Number |
Description |
Xdeclaration |
One |
Used to specify important components of an XML declaration, such as document encoding and versioning, and so on |
XElement |
One |
Specify the root element of a document |
Xdocumenttype |
One |
Represents an XML DTD |
Xcomment |
Multiple |
XML annotations. It cannot be the first argument because a valid XML document cannot start with a comment |
Xprocessinginstruction |
Multiple |
Specify any required information for an application that processes XML |
The following example creates a simple XML document that contains several elements and a property, as well as a processing instruction and some comments:
Copy Code code as follows:
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);
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?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 several methods that are the same as the XElement class, which you can refer to MSDN. It is important to note that most of the functionality for processing nodes and elements can be obtained through XElement, and only when the document-level processing is absolutely required, as well as the need to access annotations, processing instructions, and declarations, the use of the XDocument class is necessary.
After you create an XML document, you can use the Nodesafterself method to return all sibling elements after the specified XElement element. It is to be noted that this method includes only the sibling elements in the returned collection, not the descendants. This method uses deferred execution. The following code demonstrates this process:
Copy Code code as follows:
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 to Eat")
)
);
foreach (var item in root). Element ("Category"). Element ("CategoryID"). Nodesafterself ())
{
Console.WriteLine (item as XElement). Value);
}
}
The results of the implementation are as follows:
Working with classes in LINQ to XML is very simple and efficient, including creating, querying, and manipulating XML.
second, LINQ to XML Programming Concepts
This section describes the concepts associated with LINQ to XML programming, such as how to load XML, create new XML, manipulate XML information, and traverse XML documents.
1. Loading existing XML
loading XML with LINQ to XML can be obtained from a variety of data sources, such as strings, XmlReader, TextReader, or files.
The following example shows how to load XML from a file:
Copy Code code as follows:
public static void LoadFromFile ()
{
XElement root = xelement.load (path);
Console.WriteLine (Root. ToString ());
}
You can also load XML from a string using the Parse method:
Copy Code code as follows:
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 XElement object's Save method was called several times to save the XML document, which is not redundant here.
3. Create XML
In the previous example, the constructor of the XElement object was called several times to create an XML document, which is not redundant here. It is necessary to note that when you create an XML document using LINQ to XML, there is code indentation, which makes the code much more readable.
4, traversing the XML
Traversing XML in an XML tree using LINQ to XML is fairly straightforward. You only need to use the methods provided in the XElement and XAttribute classes. The elements and element methods provide a way to navigate to one or some of the elements. The following example shows how to traverse an XML tree and get the way of the specified element:
Copy Code code as follows:
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 results of the above code run are:
Is it simple? The Nodes (), Elements (), Element (name), and Elements (name) methods provide basic functionality for navigating an XML tree.
5. Manipulating XML
One important feature of LINQ to XML is the ability to easily modify XML trees, such as adding, deleting, updating, and copying the contents of XML documents.
I. Inserting
You can easily add content to an XML tree by using the Insert method of the XNode class:
Method |
Description |
Addafterself |
Add the specified content immediately after this node |
Addbeforeself |
Add the specified content immediately before this node |
In the following example, the Addafterself method is used to add a new node to an existing XML:
Copy Code code as follows:
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);
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?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 when you need to add an element to a specified node.
II. Update
The following methods can be used to update XML content in LINQ to XML:
< strong> method |
description |
replacewith |
Replaces the contents of the current element with the specified content |
ReplaceAll |
Replaces the specified content with the The child nodes of the previous element and their associated properties |
replacenodes |
Replaces the document or the child node of the current element with the specified content |
Setattributevalue |
Set the value of a property, add a property, or remove a property |
Setelementvalue |
Set child element's value, add child element, or remove a child Vegetarian |
The following example uses the ReplaceWith and Setelementvalue methods to update the XML:
Copy Code code as follows:
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);
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?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. deletion
You can use the Remove (XElement) and RemoveAll methods to delete XML.
In the following example, the RemoveAll method is used:
Copy Code code as follows:
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. RemoveAll ();
Root. Save (path);
}
Running the example will get an XML file with the following contents:
<?xml version= "1.0" encoding= "Utf-8"?>
<categories/>
In the following example, the Remove method was used to delete the description element of the XML:
Copy Code code as follows:
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);
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
</Category>
</Categories>
6, processing properties
I. Add
LINQ to XML add attributes similar to adding elements, you can use constructors or add methods to add attributes:
Copy Code code as follows:
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);
}
Running the example will get an XML file with the following contents:
Copy Code code as follows:
<?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. Retrieval
Retrieving properties can use the attribute (name) method:
Copy Code code as follows:
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 results of the above code are:
CategoryID
1
Iii. deletion
The action to delete a property is done by invoking the Remove method of the XAttribute object.
This article summarizes
This article describes the programming basics of LINQ to XML, that is, multiple LINQ to XML classes in the System.Xml.Linq namespace, which are all support classes for LINQ to XML, making it much easier to process XML than to use other XML tools. In this paper, the emphasis is on XElement, XAttribute and XDocument.
PDF download, easier to read