Read notes on the basics of LINQ-Chapter 9: getting started with LINQ to XML

Source: Internet
Author: User
Tags processing instruction

Design Principles of LINQ to XML: in order to allow most developers to operate XML more easily and effectively, Microsoft has designed a brand new method in linqto XML. From the conceptual perspective or from the perspective of memory usage and performance, LINQ to XML is a lightweight XML programming API.

In order to clearly express the design principles of LINQ to XML, we first use the most popular XML programming API-DOM to create a simple XML document, then, create the same XML document with LINQ to XML and compare the implementation methods of the two methods.

Our goal is to create an XML document that will contain detailed information about books in the linqbooks instance program.

<books>       <book>              <title>LINQ inAction</title>              <author>FabriceMarguerie</author>              <author>Steve Eichert</author>              <author>JimWooley</author>              <publisher></publisher>       </book></books>

Use Dom to generate XML documents

XmlDocument doc =new XmlDocument();XmlElement books =doc.CreateElement("books");XmlElement author1 =doc.CreateElement("author");author1.InnerText ="Fabrice Marguerie";XmlElement author2 =doc.CreateElement("author");ahthor2.InnerText ="Steve Eichert";XmlElement author3 =doc.CreateElement("author");author3.InnerText="Jim Wooley";XmlElement title =doc.CreateElement("author");title.InnerText ="LINQ in Action";XmlElement book =doc.CreateElement("book");book.AppendChild(author1);book.AppendChild(author2);book.AppendChild(author3);book.AppendChild(title);books.AppendChild(book);doc.AppendChild(books);

Use LINQ toxml to generate XML documents

new XElement("books",       new XElement("book",              newXElement("author","Fabrice Marguerie"),              newXElement("author","Steve Eichert"),              newXElement("author","Jim Wooley"),              newXElement("title","LINQ in Action"),              newXElement("publisher","Manning")       ));

Load XML

LINQ to XML allows us to load XML from a variety of different inputs, including files, URLs, and xmlreader. To load an XML file, you can use the load method of the xelement class to load an XML file to an xelement:

The load method can also load XML from a website. As follows:

XElement x = XElement.Load(@”http://msdn.microsoft.com/rss.xml”);

By default, after XML is loaded into xdocument or xelement, spaces in the document will be removed. If you want to retain spaces in the original document, you can use an overload of the load method. This overload accepts a loadoptions flag, which is used to provide options for loading XML. These options include node, preservewhitespace, setbaseuri, and setlineinfo. The following code uses loadoptions. preservewhitespace to retain spaces when loading RSS from msdn:

string xmlUrl = "http://msdn.microsoft.com/rss.xml";XElement x = XElement.Load(xmlUrl,LoadOptions.PreserveWhitespace);

The following code first loads a file named books. XML using the create static method of xmlreader. Next, traverse each of the nodes in xmlreader until a node whose nodetype is xmlnodetype. element is found. When xmlreader is located on an element node, you can call the readfrom static method of xelement and input the xmlreader to create an xelement instance.

using (XmlReaderreader = XmlReader.Create("books.xml"))            {                while(reader.Read())                {                    if(reader.NodeType == XmlNodeType.Element)                    {                        break;                    }                }                XElementbooksXml = (XElement)XNode.ReadFrom(reader);            }

If you want to create an xelement object using an XML segment contained in xmlreader, you must first use the xmlreader API to find the appropriate node and then pass the xmlreader to the readfrom method of xelement. For example, to load the first book element in the books. xml file, use the following code:

using (XmlReaderreader = XmlTextReader.Create("books.xml"))            {                while(reader.Read())                {                    if(reader.NodeType==XmlNodeType.Element&&reader.Name=="book")                        break;                }                XElementbooksXml = (XElement)XNode.ReadFrom(reader);            }

So far, we have only introduced how to load XML into xelement objects. If you want to load content such as XML declaration, XML Processing Instruction (xprocessinginstruction), XML Document Type Definition (xdocumenttype), and XML annotation (xcomment, then, the XML document should be loaded into the xdocument object instead of the xelement object. The method for loading XML to an xdocument object is similar to that for loading XML to an xelement object. The Load Static Method of the xdocument class has the same overload as the load method of the xelement, and the behavior of the two is also consistent. The only difference is that xdocument can contain subnodes of other types. For example, if we want to be able to access every sub-node in the file (including XML declaration, DTD, processing instructions, and annotations) when loading msdn RSS ), then the RSS can be loaded into the xdocument object:

XDocument msdnDoc = XDocument.Load("http://msdn.microsoft.com/rss.xml");

Create XML
LINQ to XML provides a very powerful method for creating XML elements-function creation. This method allows developers to create a complete XML tree in a statement. The XML shown below is created using LINQ to XML.

XElement xml = new XElement("books",                  newXElement("book",                      newXElement("title","LINQ in Action"),                      newXElement("author","Fabrice Marguerie"))               );

Use the imperative code structure provided in the LINQ toxml to create XML

XElement book = new XElement("book");book.Add(new XElement("title", "LINQin Action"));book.Add(new XElement("author", "FabriceMarguerie")); XElement books = new XElement("books");books.Add(book);

When creating XML, we generally need to use some namespaces and namespaces prefix in them. To provide namespace information when creating an element, you can provide the Fully expanded XML name in the first parameter of the xelement paparazzi function.
Create an xelement using a fully expanded xname

XElement book = new XElement("{http://linqinaction.net}book");

Create an xelement using xnamespace and a local name

XNamespace ns = "http://linqinaction.net";XElement book = new XElement(ns+"book");

If only one element requires a namespace, you can directly give the full extension name of the element without creating an xnamespace object. However, if several elements use the same namespace, define an xnamespace first, and then use it multiple times to make the code clearer.
Create an XML document
When using the xdocument object, you will find that many of its functions are familiar. All the methods previously mentioned that can be applied to elements can be applied to xdocument. The difference between the two lies in the type of child nodes that can be added. For xelement, its subnodes can be xelement objects, xattribute objects, xtext, ienumerable, and strings. Xdocument allows the following types of subnodes to be added:
An xdocumenttype object used to represent a DTD;
An xdeclaration object used to indicate the relevant information in the XML declaration, including the XML version, the character encoding of the document, and whether the XML document is independent;
Any number of xprocessinginstruction objects are used to provide information that will be used to process XML;
An xelement object serves as the root node of the XML document;
Any number of xcomment objects. These annotations will become the sibling node of the root node, but the xcomment object cannot be the first in the parameter list, because the XML document starting with the annotation is invalid.
Use the xdocument type and function creation mode to generate an XML document

XDocument doc = newXDocument(       newXDeclaration("1.0","utf-8","yes"),       newXProcessingInstruction("XML-stylesheet","friendly-rss.xsl"),       new XElement("rss",       new XElement("channel","mychannel")       ));

Add content to XML
LINQ to XML provides powerful support for operating existing XML files. to insert new elements or attributes into the created XML, you can use the add method. The signature of the add method is similar to that of the xelement method-it also provides two overloading methods. The first overload only accepts a single object, and the second overload allows simultaneous insertion of a series of objects.

public voidAdd(object content)public voidAdd(params object[] content)

The two reloads of the add method above allow us to continue using the familiar function creation mode. To add an element as a subnode of an existing xelement, use the following code:

XElement book = newXElement("book");book.Add(newXElement("author","Dr. Seuss"));

Of course, any type that can be used as an xelement subnode can be passed to the above content parameter. For example, to add an attribute to the current xelement, we can pass an xattribute object to the add method.

XElement book = newXElement("book");book.Add(newXAttribute("publicactioniDate","October 2005"));

Add content for xelement using the Add Method

XElement books = newXElement("books");books.Add(newXElement("book",              newXAttribute("publicactionDate","May 2006"),              newXElement("author","Chris Sells"),              newXElement("title","Windows Forms Programming")       ));

In addition, the add method can automatically process the passed ienumerable object. If the add method detects that its parameter implements ienumerable, each element in the ienumerable will be added to the current xelement in sequence. This feature allows you to use LINQ to query XML structures, because standard query operators and all XML query methods provided by LINQ to XML can return ienumerable <xelement>. The following code cleverly uses the add method to support ienumerable and Adds all elements in the existing XML document to another xelement.

XElementexistingBooks = XElement.Load("ss.xml");XElement books = newXElement("books");books.Add(existingBooks.Elements("book"));

By default, when a new element is added to an xelement, the element is added to the last position. If the inserted content is xelement, the element is used as the last subnode of the xelement. If the inserted content is xattribute, this element is used as the last attribute of xelement. If this implementation does not meet your actual requirements, you can also use other adding methods provided by xelement. For example, if you want to add an element at the beginning, that is, add it as the first subnode of xelement, you can call the addfrist method. If you want to more accurately specify the insert position of an element, You can first navigate to the insert position, and then call addafterself or addbeforeself. For example, if you want to add a book element as the second subnode of the xelement books, you can use the following code:

XElement newBook =new XElement("book","LINQ in Action");XElement firstBook =books.Element("book");firstBook.AddAfterSelf(newBook);

Remove content from XML
Xelement provides several methods to remove its neutron elements. The most direct one is to first locate the element and call its remove method. The remove method can be used on a single element or on ienumerable. You can call the Remove Method on ienumerable to remove all elements contained in it at one time. The following code demonstrates how to remove a book element and all book elements.

books.Element("book").Remove();books.Elements("book").Remove();

Another less intuitive method of removing elements is to call the setelementvalue method of xelement-pass in null as its parameter.

Books.SetElementValue(“book”,null);

If you only want to remove the content from the element but still keep the label of the element, you can use the element's vlaue attribute. We can first find this element and set its value attribute to an empty string:

books.Element("book").Element("author").Value= String.Empty;

Update XML content
Setelementvalue method to update the content of a node

XElement books = newXElement("books.xml");book.Element("book").SetElementValue("author","BillGates");

Note that setelementvalue only supports Simple content. If the input is not a string, setelementvalue will try to use the getstringvalue method of xcontainer to convert it to a string. Set the author element value to an xelement as follows:

books.Element("book").SetElementValue("author",newXElement("foo"));

Xcontainer throws an exception because it does not support using xobject and its derived class as the content.
To process more complex content, use the replacenodes method defined in xcontainer.
Replacenodes supports various types of content and multiple parameters. Therefore, modify setelementvalue in the above Code to replacenodes:

books.Element("book").Element("author").ReplaceNodes(newXElement("foo"));

The replacenodes method of xelement can remove all child elements from the element and use the passed parameters as its new content. The content parameter can be any object that can be used as a child element of xelement, including ienumerable (each element will be added once ). Replacenodes also provides an overload that can accept multiple parameters and allow them to replace the original content of the element at a time. As follows:

books.Element("book").ReplaceNodes(       new XElement("title","Ajaxin Action"),       newXElement("author","Dave Crane"));

Operation attribute
The xattribute class is used to represent attributes in XML in LINQ to XML. Unlike other XML APIs described earlier, attributes and elements/nodes come from different inheritance systems. In linqto XML, the attribute is just a simple name/value pair. Therefore, the constructor of the xattribute object accepts name and value as parameters accordingly.
When creating XML, we can pass the attribute as a parameter to the function creation statement or add method. For example, if you want to add a publication date attribute to the book element, you can use the following statement during creation:

newXElement("book",new XAttribute("pubDate","July31,2006"))

Or call the add method after the creation is complete to pass the attribute to the content parameter of the method:

book.Add(newXAttribute("pubDate","July 31,2006"));

In addition to the add method, you can also use the setattributevalue method of the element to set its attributes. The setattributevalue method is similar to the setelementvalue method described earlier. It is used to add or modify attributes for an existing xelement. If this attribute already exists in xelement, its value will be updated. If it does not exist, it will be added. For example, to change the value of the pubdate attribute, you can use the following code to call the setattributevalue method:

book.SetAttributeValue("pubDate","October1,2006");

Similar to setelementvalue, if null is input, setattributevalue can remove an attribute of an element. In addition, xattribute provides a remove method to remove an attribute.

Book.Attribute(“pubDate”).Remove();

Save XML
The method for saving XML is intuitive. The xelement and xdocument classes provide the Save method to save XML to files, xmltextwriter, or xmlwriter. If you want to store xelement on a disk, you can call the Save method and input the path of the XML file. For example, Book. Save (@ "C: \ books. xml ");
 
Summary
The built-on-LINQ to XML allows us to query XML files using standard query operators. LINQ toxml provides several easy-to-use and powerful methods to query XML elements. The conciseness of APIS is comparable to the powerful query functions of LINQ to XML, which greatly improves the programming experience of developers.
LINQ to XML is a lightweight xmlapi specially designed for LINQ. It is built on the language innovation brought about by LINQ and introduces some brand-new concepts, including function creation, context-independent XML creation, and simplified XML commands. Although Microsoft can improve the original xml api to support LINQ, the brand-new, er Design of LINQ to XML completely frees the API from the shackles of the original framework, this greatly facilitates the XML operations in LINQ.
The core class in LINQ to XML is xelement. In addition, linqto XML provides important classes such as xattribute, xdocument, and xname. By using these core classes with programming APIs, linqto XML provides a complete set of methods for loading, parsing, creating, updating, and saving XML.

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.