LINQ to XML node lookup Delete Modify implementation code

Source: Internet
Author: User
Tags abstract foreach httpcontext
This article does not introduce its concept in detail, instead of speaking in the. NET how to manipulate the XML file. To point out, XML is a subset of standard generic Markup Language (SGML) that can be run across platforms and is ideal for web transmissions, in different programming languages (PHP, Java,. NET, etc.) inside are widely used, so the operation of XML, you will have to master a technology.
Let's look at what the XML document looks like, and here's how to illustrate the following figure. XML can be used to describe data definitions, types, etc., which are typically used for data storage and transmission.
Figure I
Use the following method to generate the XML file above, generate an XML file, you can use the XDocument inside the save method, you can also use the XElement inside the Save method:
 
 
The code is as follows Copy Code
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Xml;
Using System.Xml.Linq;
Namespace LINQTOXML2 {class Program {static void Main (string[] args) {XDocument doc
                    = new XDocument (New Xdeclaration ("1.0", "UTF-8", "true"), New XElement ("Root00", New XElement ("Root10", New XAttribute ("Color", "Green"), "Ellipse"), n EW XElement ("Root11", New XAttribute ("Color", "white"), New XAttribute ("VA Lue "," quadrilateral "), New XElement (" Root20 ", New XAttribute (" Color "," Purple ") , "Diamond"), New XElement ("Root21", New xattr Ibute ("Color", "Red"), "trapezoid"), New XElement ("Root12", New XAttribute ("Color"),

            "Orange"), "triangle")); Doc.
 Save ("Http://www.cnblogs.com/Shape.xml");////Use this method to store the XML document in the file       }
    }
} 
Note: Here is a question about the path to save, here is the way to use the Http://www.cnblogs.com/Shape.xml, this represents the upper level of the directory, because in the console application of the default environment running, it is located in the project bin
In the debug directory, so it's two level directory is just the root directory, and we placed the Shape.xml in the root directory. And for like Server.MapPath and HttpContext.Current.Server.MapPath, you can
Simple according to the following summary method to use, such as the summary of the following I was based on the information on the Internet to collect, what is wrong, welcome to point out.
1. Define a page code that inherits from the Page class, which includes Aspx.cs and the ASPX page, because both ASPX and Aspx.cs are the same local class, which can be used with Server.MapPath. Because
Server.MapPath is written in full: This.Page.Server.MapPath.

2. Use HttpContext.Current.Server.MapPath in the class that inherits from page (. cs) Because this class does not have a page instantiation and cannot be specified to a specific page, This.Page.Server.MapPath, One is through the object
Call (this), one is called Through the Class (HttpContext.Current, (current page)), because the page class is not normally instantiated when using HttpContext.Current.
The resulting data content is as follows: (Save as Shape.xml):
 
  code is as follows replication code
 
 <?xml version=" 1.0 "encoding=" Utf-8 "?> <root00&
  Gt <root10 color= "Green" > Ellipse </Root10> <root11 color= "white" value= "quadrilateral" > <root20 color= "Purple" > Diamond </Root20> <root21 color= "Red" > trapezoid </Root21> </Root11> <root12 color= "Orange" > Triangle < /root12> </root00> 
   
Here is a brief introduction:
The first sentence ( 
  <?xml version= "1.0" encoding= "Utf-8"?> ), which is a statement declared as XML, is to tell the browser that the document that will be processed is an XML file. 
  but XML declarations are optional in XML documents , which means that there is no XML declaration statement, and sometimes it is possible. But we can not do this here, because our XML document contains 
  Chinese (Chinese encoding is GBK, GB2312 or utf-8), if not stated, open in the browser will be an error. 
  
The second sentence ( 
  <Root00>...</Root00> ), which is the root element, is the only one in an XML document, which is the parent element of all elements. 
  
The third sentence ( 
  <root10 color="green" > Ellipse </Root10>Root10 Properties, green is the attribute value, and the ellipse is the element value.) It's easy to understand that the attribute is inside the angle bracket of the element, and the element value is between the two angle brackets of the element. Because the attribute can be multiple, and the element value is one, so the design should also be very easy to remember. The following statement is basically similar to the previous, which I want to talk about is the parent element, the child element, these are only relative. For example, Root11 with Root00, Root11 is a child element, and to Root20 or Root21, Root11 is the parent element.
OK, double-click Shape.xml, and you can see the results shown in the following figure: 
   
, which Root10 is the element of the root element Root00, color is
Figure II
As you can see, this is no different from what we wrote in the XML file. I've already put some of the XML terminology in the first picture.
, such as the root element , the element , the attribute , which already has the corresponding content in figure one. In fact, XML contains a lot of other content, but the content of this article is compared to the basis, not involved in the content is not explained.
Within. NET, there are several ways to implement XML document operations. Limited to space, which only describes the way LINQ to XML is.
First of all, the main introduction of the next System.linq.xml Dynamic class library Inside some of the commonly used methods, online link address for
System.Xml.Linq namespaces , which you can see in the MSDN details to help you understand.
Figure Three
From the diagram above you can see that the System.Xml.Linq.XObject class is the base class for LINQ to Xml, which is an abstract class.
Both the System.Xml.Linq.XAttribute and System.Xml.XNode classes inherit from the Xobject class. Xobject contains constructors, properties, and methods that are not
List it again, because it's not what we're going to be introducing here. If you want to learn more, you can view the MSDN Help documentation.
Figure Four
Figure three and figure four are posted because we're going to be introducing the following two abstract classes (Xobject and XContainer). The operation is respectively
The class xattribute of the attribute, the class xelement of the action element, and the class XDocument of the operation document.
The first is the XDocument and XElement classes, these two classes are actually quite similar. Because they both inherit from the XContainer abstract class. So
Both have properties and methods that abstract class XContainer have. XDocument represents an XML document, while XElement represents an XML element. This
Only one of their static function load is described. This will be a simple example to introduce the use of these common methods. This inside we will load the above
Describes the Shape.xml file. Let's look at the simple console code:
The code is as follows Copy Code
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Xml;
Using System.Xml.Linq;

Namespace LINQTOXML2
{
    class program
    {
        static void Main (string[] args)
        {

            XDocument Shapedoc = Xdocument.load ("Http://www.cnblogs.com/Shape.xml");
            Console.WriteLine (Shapedoc);

            XElement shapeelement = xdocument.load ("Http://www.cnblogs.com/Shape.xml");
            Console.WriteLine (shapeelement);}}
About the XDocument class and the XElement class static Load method, which returns a XDocument (XML document) object, the latter (which isStatement of the annotation) returns a XElement (XML element) object. The above code is loaded from the contents of the XML file, but it is important to note that XDocument loading way than the XElement, single from the elements, the XDocument load contains the root element.
These two different loading methods, you can choose the way you want to the XML file to load the corresponding content. Generally speaking, the way we use it is to load the elements, because we can manipulate the elements directly.
The way above is to generate an XML document and load the objects that need to be manipulated, and the following will be done in a simple way to implement LINQ to XML additions and deletions to the instance. And right.
Face some common methods to do a simple description.
Check:
The code is as follows Copy Code
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Using System.Xml; Using System.Xml.Linq; Namespace LINQTOXML2 {class Program {static void Main (string[] args) {XElement doc = xelement.load ("Http://www.cnblogs. Com/shape.xml "); ienumerable<xelement> elements = doc. Elements (); foreach (var elment in elements) {Console.WriteLine (elment. ToString ()); } console.read (); } } }
Query, which is the element that traverses the XML document, and the results of this output are shown below.
 
  
  
The code is as follows Copy Code
<root10 color= "Green" > Ellipse </Root10>
<root11 color= "white" value= "quadrilateral" >
  <root20 color= " Purple "> Diamond </Root20>
  <root21 color=" Red "> trapezoid </Root21>
</Root11>
< Root12 color= "Orange" > Triangle </Root12>
In contrast to the original XML document (Shape.xml), we can see that the node returned by the Elements () method does not contain the root node Root00, and the root node is also not available with element ("element name"). element , which is thefirst (in document order) child element with the specified element name . The first child element in this case is the first child element when it contains a child element with multiple identical element names. The element below the root element is considered a child element, and the root element is not a child element. Of course, the first child element does not mean that there is only one element. Can be an element that contains other elements. The Elements () method returns a collection of child elements of this element or document in document order. Obviously, generating a XElement object can have two implementations of the square . The Elements () method returns a collection of child elements of a document, in this way, by loading it from within the document. Note that the root element is not a child element, the root element is not returned here, and another way is through the new XElement (.. To generate the XElement object, so that it will return this element. This requires no consideration of the root element.
Increase:
 
 
The code is as follows Copy Code
   
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Xml;

Using System.Xml.Linq;  Namespace LINQTOXML2 {class Program {static void Main (string[] args) {XElement doc

            = Xelement.load ("Http://www.cnblogs.com/Shape.xml");

            XElement add = new XElement ("Root13", New XAttribute ("Color", "Yellow"), "star"); 
 Doc. 
add;
//doc. Element ("Root10").
             addbeforeself (add);  Doc. Element ("Root10").

             addafterself (add);  var elements = from E in Doc. 

            Elements () select (e);
            foreach (var elment in elements) {Console.WriteLine (elment);
        } console.read (); }} 
   
Above is a simple way to add XML elements, first to introduce ways to add XML elements. First introducedAdd (Object) method, which willThe specified content is added as a child of the xcontainer. The xcontainer here refers to the inheritance from XContainer. and XDocument and XElement both inherited from Xconatainer. XContainer, my understanding is the child of the root element. Don't know if it's wrong?
This also introduces another two added methods, namely the Addafterselt (object) method and the addbeforeself (object) method. The former adds the specified content immediately after the node , and the latter is added immediately after the node. The use of these two methods is visible above the annotation. Their use requires you to first navigate to a node (like Doc above) . Element ("Root10"). addafterself (add); Before you can select whether to increase before or after this node. The following display results are no longer duplicated, as the above code runs in the console and results.
By deleting:
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Using System.Xml; Using System.Xml.Linq; Namespace LINQTOXML2 {class Program {static void Main (string[] args) {XElement doc = xelement.load ("Http://www.111cn.ne T/rss.xml "); var elements = from E in Doc. Elements ()//Where (E.element ("Root12"). Value = = "triangle")//select (e); Elements. Remove (); Doc. Element ("Root11"). Element ("Root21"). Remove (); Console.WriteLine (DOC); Console.read (); } } }
To delete a node is to use the XElement remove () method, which is given in Chinese to remove this node from the parent of the node . To be blunt, the node is deleted, but if it is the root node, it will not be deleted, only the child node is deleted.
You can look at the above two deleted statements, where the deletion of annotations, is a more restrictive way, and note the following through a node to the next knot in such a way to locate the deletion, this way is more flexible.
change: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; u Sing System.Xml.Linq; Namespace LINQTOXML2 {class Program {static void Main (string[] args) {XElement doc = xelement.load ("Http://www.cnblogs. Com/shape.xml "); Doc. Element ("Root11"). Setelementvalue ("Root21", "Square"); (1) Doc. Element ("Root11"). Element ("Root21"). setattributevalue ("Color", "Blue"); (2) Doc. Element ("Root11"). Element ("Root21"). replacewith (New XElement ("Root22", "Square"); Console.WriteLine (DOC); Console.read (); } } }

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.