In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to get started with LINQ to XML quickly, in view of this problem, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
There are many techniques for operating XML:
1) DOM (Document Object Model, document object Model), which provides a standard parsing for XML documents.
2) XPath and XSLT, which provide the ability to query and format XML.
3) the .NET Framework provides classes that operate on XML (under the System.XML namespace).
4) LINQ to XML.
In my opinion, with LINQ to XML technology, other technologies for manipulating XML in .NET can be abandoned, because LINQ to XML manipulating XML is simpler, more convenient and more intuitive than other technologies.
LINQ to XML is LINQ-based, so you can use all the features of LINQ, such as standard query operators (see "LINQ Standard query operator details" for details) and LINQ's programming interface. Using LINQ to XML, you can easily load the XML file into memory, query, modify and delete the nodes in the XML document, and then easily save the XML document back to disk.
The namespace of System.Xml.Linq contains all the classes that LINQ to XML uses to process XML, with a total of 19 classes, as shown below.
Class description
Extensions contains LINQ to XML extension methods.
XAttribute represents a XML feature.
XCData represents a text node that contains CDATA.
XComment represents an XML comment.
XContainer represents a node that can contain other nodes.
XDeclaration represents a XML declaration.
XDocument represents an XML document.
XDocument Type stands for XML document type definition (DTD).
XElement represents a XML element.
XName represents the name of the XML element or feature.
XNamespace represents a XML namespace. This class cannot be inherited.
XNode represents the abstract concepts (elements, comments, document types, processing instructions, or text nodes) of nodes in the XML tree.
XNodeDocumentOrderComparer includes the ability to compare the document order of nodes. Cannot inherit this class.
XNodeEqualityComparer compares nodes to determine if they are equal. Cannot inherit this class.
XObject represents a node or property in the XML tree.
XObjectChangeEventArgs provides data about Changing and Changed events.
XProcessingInstruction stands for XML processing instruction.
XStreamingElement represents an element in the XML tree that supports deferred stream output.
XText represents a text node.
These 19 classes provide a lot of methods, in fact, few people will learn the details of each method when learning LINQ to XML, the purpose of this article is to let children's shoes that have never used LINQ to XML get started quickly when they need to use LINQ to XML technology, and then use it in their own program development, so this article only talks about LINQ to XML to deal with the three most commonly used and most used classes in XML classes, namely XDocument, XElement and XAttribute.
The XDocument class derives from the XContainer class, so it can have child nodes, but the XML standard restricts XDocument objects to contain only a single XElement child node, because XML documents allow only one root node.
XDocument provides processing of valid XML documents, including declarations, comments, and processing instructions.
A XDocument can contain the following elements:
1) A XDeclaration object. XDeclaration enables you to specify the relevant parts of the XML declaration: the XML version, the encoding of the document, and whether the XML document is independent.
2) A XElement object. This is the root node of the XML document.
3) any number of XProcessingInstruction objects. Processing instructions pass information to the application that processes the XML.
4) any number of XComment objects. The comment will be at the same level as the root element. The XComment object cannot be a * * parameter in the list because the XML document begins with a comment.
5) A XDocumentType for DTD.
The methods provided by the XDocument class can refer to the MSDN documentation.
XElement is derived from XContainer, and XContainer is derived from the XNode class, so an element is also a node. Through XElement, you can create XML elements, add and modify, and remove elements and child elements.
The XElement class provides a lot of methods, because the core thing in an XML document is XElement, which makes it easy to deal with XML offerings as if they were in the bag.
The methods provided by the XElement class can refer to the MSDN documentation.
XAttribute is derived from the XObject class, not from the XNode class, so XAttribute cannot be a node in the XML tree, it is a name / value pair associated with XElement, that is, XAttibute cannot exist independently of the element.
The methods provided by the XAttribute class can refer to the MSDN documentation.
This article focuses on how to use LINQ to XML technology to manipulate XML documents, including how to create an XML document, how to save XML documents, how to traverse XML document elements, how to find XML document elements, how to update XML document elements, how to delete XML document elements, etc., below we assume an application scenario to use LINQ to XML technology to achieve the various operations just mentioned.
Scene: save the information of Chinese provinces, cities and regions in an XML document, you can easily carry out various operations on the document, such as query, update, delete elements, and so on.
Let's first create the relevant classes of provinces, cities and regions, as follows:
Public class Province {/ province name / public string Name {get; set;} / provincial capital / public string Capital {get; set }} public class City {/ City name / public string Name {get; set;} / City number / public string Code {get; set;} public Province Province {get; set }} public class District {/ area name / public string Name {get; set;} / description / public string Description {get; set;} public City City {get; set;}}
1) how to create an XML document that stores the information of provinces, cities and regions in China.
Creating an XML document using LINQ to XML is very simple, with the following code:
Static void Main (string [] args) {/ / get the path to the Area.xml file in the current application directory string _ filePath = Path.Combine (System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Area.xml"); FileInfo fiXML = new FileInfo (_ filePath) / / if the file does not exist if (! (fiXML.Exists)) {XDocument xelLog = new XDocument (new XDeclaration ("utf-8", "yes"), new XComment ("XML File For AREA"), new XElement ("Provinces") New XElement ("Province", new XAttribute ("Name", "province"), new XElement ("City", new XAttribute ("Name", "city"), new XElement ("District", new XAttribute ("Name") "Administrative region") XelLog.Save (_ filePath);}}
This code initializes a new instance of the XDocument class with the specified content, and then calls the Save method of XDocument to generate an XML document. XDocument is rarely used to create a XML tree, usually using the XElement root node to create a XML tree. Unless there are specific requirements for creating a document (for example, processing instructions and comments must be created in * *, or document types must be supported), it is usually more convenient to use XElement as the root node. Running this code creates a document called Area.xml in the root directory of the generated application, with the following contents:
2) how to load a XML tree into program memory.
First of all, we need to load a XML document into the program's memory. In LINQ to XML, we usually use the Load method of type XElement to load the XML tree of the XML document from the root node into an object of type XElement, and then we can use various methods provided by XElement to perform various operations on this in-memory XML document.
We create a LINQtoXML helper class, LinqToXmlHelper.cs, in which we write all the methods related to the XML operation. Here is a method to load the XML document into the XElement object.
/ load the Area.xml document into a XElement object of type xElement in memory. After a successful call to the XElement.Load method, the entire XML tree is saved in xElement / public XElement Load () {XElement xElement = XElement.Load (_ filePath); return xElement;}
We have just created an XML document, and now we load the document into memory and print the XElement object.
Static void Main (string [] args) {LinqToXmlHelper linqToXmlHelper = new LinqToXmlHelper (); var elements = linqToXmlHelper.Load (); string str = elements.ToString (); Console.WriteLine (str); Console.ReadKey ();}
The output is as follows:
3) how to insert new elements into an existing XML document
Now that we know how to create and load XML documents in LINQ to XML, the next problem is how to add new nodes to an existing XML document. Here is how to add new elements. We can add the new provincial city and region information to the Area.xml document, and update it if it already exists. Here, we use XElement's Save to save the changed XML document.
Add a new element. If the Description to be added already exists, update the Description of the zone / public void AddElement (IList districts) {if (districts==null | | districts.Count==0) return; XElement xElement = Load () Foreach (District district in districts) {if (district.City = = null | | district.City.Province = = null) {continue;} XElement provinceElement = xElement.Elements ("Province") .Where (e = > ((string) e.Attribute ("Name")) .equals (district.City.Province.Name). FirstOrDefault () / / determine whether the province exists. There is no node if (provinceElement==null) {provinceElement= new XElement ("Province", new XAttribute ("Name", district.City.Province.Name), new XAttribute ("Capital", district.City.Province.Capital)); xElement.Add (provinceElement) } XElement cityElement = provinceElement.Elements ("City") .Where (e = > ((string) e.Attribute ("Name")) .equals (district.City.Name)) .FirstOrDefault () / / determine whether the city exists. If it does not exist, add the nodes of the city if (cityElement==null) {cityElement= new XElement ("City", new XAttribute ("Name", district.City.Name), new XAttribute ("Code", district.City.Code)); provinceElement.Add (cityElement) under the corresponding province. } XElement districtElement = xElement.Elements ("District") .Where (e = > ((string) e.Attribute ("Name")) .equals (district.Name)) .FirstOrDefault () / / if there is a node in this area, delete it first, and update the node if in this way: {districtElement.Remove ();} districtElement = new XElement ("District", new XAttribute ("Name", district.Name), new XAttribute ("Description", district.Description)) CityElement.Add (districtElement);} / / after the operation, save the XML tree in memory back to the XML document on the hard disk. XElement.Save (_ filePath);}
In the AddElement method above, by calling the Add method of the XElement object that passes a XElement object, you can add a XElement object (node) as the last child of an existing node. In this way, we can easily extend the children of a node through Add.
Next, call the add new element AddElement method, save the collection information of an extent to the Area.xml document, and then print the XML tree. The code is as follows:
Static void Main (string [] args) {LinqToXmlHelper linqToXmlHelper = new LinqToXmlHelper (); Province province = new Province () {Name = "Guangdong", Capital = "Guangzhou"}; City city = new City () {Name = "Guangzhou", Code = "020", Province = province} IList districts = new List () {new District () {City = city, Name = "Tianhe District", Description = "description of Tianhe District"}, new District () {City = city, Name = "Yuexiu District" Description = "description of Yuexiu District"}} LinqToXmlHelper.AddElement (districts); XElement xElement = linqToXmlHelper.Load (); Console.WriteLine (xElement.ToString ());}
The output is shown in the figure:
4) how to query and traverse the elements of an XML document
According to the Elements method provided by the XElement type, we can obtain all the child node elements of a node, or we can obtain a collection of all nodes under a node that match the parameter node name by passing the node name as a parameter, and we can obtain the attribute information of a node according to the Attibute method provided by the XElement type. The following code example queries the information of all the districts under the city based on the city name:
/ query the information of all districts under the city according to the city name / public IList GetDistricts (string cityName) {IList districts = new List (); XElement xElement = Load () / / get all the children of the node named cityName in the city IEnumerable xElementxElements = xElement.Elements ("Province") .Elements () .Where (e = > ((string) e.Attribute ("Name")) .equals (cityName)) .Elements (); foreach (XElement element in xElements) {District district = new District () District.Name = (string) element.Attribute ("Name"); district.Description = (string) element.Attribute ("Description"); districts.Add (district);} return districts;}
Call the GetDistricts method
Static void Main (string [] args) {LinqToXmlHelper linqToXmlHelper = new LinqToXmlHelper (); IList districts = linqToXmlHelper.GetDistricts ("Guangzhou"); foreach (var district in districts) {Console.WriteLine (district.Name);}}
The output is as follows:
Tianhe district
Yuexiu District
5) how to delete node elements in an XML document
The method of deleting the node element of an area, where the name of the assumed area is unique
/ / delete the node element of the zone, where the name of the hypothetical zone is unique / public void DeleteElement (IList districts) {XElement xElement = Load () Foreach (District district in districts) {XElement districtElement = xElement.Elements ("Province"). Elements ("City"). Elements ("District") .Where (e = > ((string) e.Attribute ("Name")) .equals (district.Name)) .FirstOrDefault () If (districtElementautomatically null) {districtElement.Remove ();}} xElement.Save (_ filePath);}
Call the XElement.Remove method to delete the current node on the parent of the current node. The following code deletes the node named "Yuexiu area" in the zone node.
Static void Main (string [] args) {LinqToXmlHelper linqToXmlHelper = new LinqToXmlHelper (); IList districts = new List () {new District () {Name = "Yuexiu District"}}; linqToXmlHelper.DeleteElement (districts); XElement xElement = linqToXmlHelper.Load (); Console.WriteLine (xElement.ToString ()); Console.ReadKey () }
The output is as follows:
So far, you have seen LINQ to XML technology to operate some of the most common functions of XML, including creating and loading XML documents, adding, deleting and updating XML nodes, and so on.
This is the answer to the question about how to get started with LINQ to XML quickly. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel to learn more about it.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.