Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a xml using LINQ to XML

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to create a xml using LINQ to XML. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. LINQ to XML class

The following code demonstrates how to use LINQ to XML to quickly create a xml:

Hide the line number copy code? 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);}

Running the example will result in a xml file with the following contents:

Root2, XElement class

The XElement class is one of the basic classes in LINQ to XML. It represents a XML element. You can use this class to create elements, change element contents, add, change, or delete child elements, add attributes to elements, or serialize element contents in text format. You can also interoperate with other classes in System.Xml, such as XmlReader, XmlWriter, and XslCompiledTransform.

There are many ways to create xml documents using LINQ to XML, depending on your actual needs. The easiest and most common way to create an xml document is to use the XElement class. The following code demonstrates how to create an xml document using the XElement class:

Show line number copy code? 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);}

Running the example will result in a xml file with the following contents:

57485174-46fc-4e8c-8d98-d25b53d504a1 Beverages 1474dde1-8014-48f7-b093-b47ca5d5b770 Condiments 364224e0-e002-4939-90fc-0fd93e0cf35b Confections

The XElement class contains a number of methods that make it easy to deal with xml. Refer to MSDN for these methods.

Among them, Save, CreateReader, ToString and WriteTo are the three most commonly used methods:

3. XAttribute class

The XAttribute class is used to handle the attributes of an element, which are name-value pairs associated with an element, and there can be no attributes with duplicate names in each element. Using the XAttribute class is very similar to using the XElement class, and the following example shows how to add an attribute to the xml tree when it is created:

Show line number copy code? 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;}

Running the example will result in a xml file with the following contents:

Beverages Condiments Confections

There are few methods of the XAttribute class, and the three commonly used ones are:

The following example uses Remove to remove the CategoryID attribute of the first element:

Show line number copy code? 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);}

Running the example will result in a xml file with the following contents:

Beverages Condiments Confections

As an attempt, try the following ways to delete attributes:

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

Running the example will throw a null reference exception because the element Categories does not have an attribute called CategoryID.

4. XDocument class

The XDocument class provides methods for processing xml documents, including declarations, comments, and processing instructions. A XDocument object can contain the following:

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") New XElement ("Gender", "M"), new XComment ("more comments")) Xdoc.Save (path);}

Running the example will result in a xml file with the following contents:

Scott Klein Geek 02/05/2007 M

The XDocument class contains several of the same methods as the XElement class, which can be found in MSDN. It is important to note that most of the functionality for processing nodes and elements is available through XElement, and it is only necessary to use XDocument classes when document-level processing power is absolutely needed and when you need access to comments, processing instructions, and declarations.

After you have created the xml document, you can use the NodesAfterSelf method to return all sibling elements after the specified XElement element. It is important to note that this method includes returning only sibling elements in the collection, not children. This method uses deferred execution. The following code demonstrates this process:

Show line number copy code? 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 to eat") Foreach (var item in root.Element ("Category"). Element ("CategoryID"). NodesAfterSelf () {Console.WriteLine ((item as XElement) .value);}} II. LINQ to XML programming concept

This section introduces concepts related to LINQ to XML programming, such as how to load xml, create a new xml, manipulate xml information, and traverse xml documents.

1. Load the existing xml

Loading xml using 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:

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 has been called several times to save the xml document, so I won't go into detail here.

3. Create xml

In the previous example, the constructor of the XElement object was called several times to create an xml document, so I won't go into detail here. It is important 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 xml

Using LINQ to XML to traverse the xml in the xml tree is fairly simple. 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 more elements. The following example shows how to traverse the xml tree and get 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 the above code running is:

Isn't it easy? The Nodes (), Elements (), Element (name), and Elements (name) methods provide basic functions for navigation of xml trees.

5. Manipulate xml

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

Using the insert method of the XNode class, you can easily add content to the xml tree:

In the following example, use the AddAfterSelf method to add a new node to the existing xml:

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);}

Running the example will result in a xml file with the following contents:

1 Beverages 2010-01-31T03:08:51.813736+08:00 Soft drinks, coffees, teas, beers, and ales

You can use the AddBeforeSelf method when you need to add an element before a specified node.

ii. Update

There are several ways 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);}

Running the example will result in a xml file with the following contents:

2 test data Soft drinks, coffees, teas, beers, and ales

iii. Delete

You can use the Remove (XElement) and RemoveAll methods to delete the xml.

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);}

Running the example will result in a xml file with the following contents:

In the following example, the Description element of xml is removed using the Remove method:

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);}

Running the example will result in a xml file with the following contents:

1 Beverages 6, processing properties

i. Add

LINQ to XML adding attributes is similar to adding elements, you can use constructors or Add methods 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);}

Running the example will result in a xml file with the following contents:

Beverages Soft drinks, coffees, teas, beers, and ales

ii. Search

You can use the Attribute (name) method to retrieve properties:

Show line number copy code? 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, thank you for your reading! This is the end of this article on "how to use LINQ to XML to create xml". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report