The XElement class is one of the basic classes in LINQtoXML. 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. 1. LINQ to XML class
Hide row number? Create XML
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:
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:
Show row number? This is a piece of program code.
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:
57485174-46fc-4e8c-8d98-d25b53d504a1
Beverages
1474dde1-8014-48f7-b093-b47ca5d5b770
Condiments
364224e0-e002-4939-90fc-0fd93e0cf35b
Confections
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:
Show row number? This is a piece of program code.
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:
Beverages
Condiments
Confections
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:
Show row number? This is a piece of program code.
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:
Beverages
Condiments
Confections
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:
Scott Klein
Geek
02/05/2007
M
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:
Show row number? This is a piece of program code.
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.WriteLi
You can also use the Parse method to load xml from a string:
public static void LoadFromString() { XElement root = XElement.Parse(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
"); 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:
In the following example, add a new node to the existing xml using the AddAfterSelf method:
public static void AddAfterSelf(){ XElement root = XElement.Parse(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
"); 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:
1
Beverages
2010-01-31T03:08:51.813736+08:00
Soft drinks, coffees, teas, beers, and ales
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(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
"); 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:
2
test data
Soft drinks, coffees, teas, beers, and ales
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(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
"); root.RemoveAll(); root.Save(path); }
Run this example to get an xml file with the following content:
In the following example, the Remove method is used to delete the Description element of xml:
public static void Remove(){ XElement root = XElement.Parse(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
"); root.Element("Category").Element("Description").Remove(); root.Save(path);}
Run this example to get an xml file with the following content:
1
Beverages
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:
Beverages
Soft drinks, coffees, teas, beers, and ales
II.Search
You can use the Attribute (name) method to retrieve attributes:
Show row number? This is a piece of program code.
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:
CategoryID1
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.
The above is a detailed introduction to the graphic code of the basics of programming with LINQ to XML. For more information, see The PHP Chinese network (www.php1.cn )!