In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to generate XML elements or XML documents in C#", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "how to generate XML elements or XML documents in C#" it!
I. Overview
Overview-LINQ to XML | Microsoft official document
LINQ to XMLLINQ to XML is a LINQ-enabled in-memory XML programming interface that allows you to process XML in the .NET Framework.NET Framework programming language.
You need to add a reference to System.Xml.Linq.dll when using LINQ to XML.
The XElement class represents the XML element, which is a derivative of the XContainer class, while the XContainer class derives from the XNode class. An element is a node.
XElement is one of the most important and basic classes of LINQ to XML, and it contains all the functions necessary to create and manipulate XML elements. Through it, you can create elements, add and modify attributes of elements, manipulate the contents of elements, and so on.
The XAttribute class is used to handle attributes, which are name / value pairs associated with an element.
The XDocument class provides methods for processing valid XML documents, including declarations, comments, and processing instructions. The XDocument class is derived from the XContainer class and can have child nodes. The XML standard limit XDocument object contains only a single XElement child node, which is the root node or follower element.
Inheritance relationship:
Derived classes of XNode (abstract) class are: XText, XComment, XDocumentType, XProcessingInstruction, XContainer
The derived classes of XContainer (abstract) class are: XElement, XDocument.
2. Load XML file 1, input XML data / / 1 from the file, obtain XML data from URI, support local path and URL, and support the corresponding enumeration settings XElement xe1 = XElement.Load (@ "D:\ 123.xml", LoadOptions.None); / / 2, load XmlReader xr = XmlReader.Create (@ "D:\ 123.xml") from XmlReader; XElement xe2 = XElement.Load (xr) / / 3. Get data from TextReader TextReader reader = File.OpenText (@ "D:\ 123.xml"); XElement xe3 = XElement.Load (reader); / / 4. Read XElement xe4 = XElement.Load (new FileStream (@ "D:\ 123.xml", FileMode.Open, FileAccess.Read) from Stream; 2. Enter XML data string xmlString = "Liu Bei 28" from string; XElement xe = XElement.Parse (xmlString, LoadOptions.SetLineInfo) Generate XML elements or XML documents 1. Create XML elements XElement xml = new XElement ("Persons", new XElement ("Person", new XElement ("Name", "Liu Bei"), new XElement ("Age", "28"), new XElement ("Person", new XElement ("Name", "Guan Yu") New XElement ("Age", "27")) Xml.Save (@ "D:\ 123.xml"); 2. Create XML document / / create processing instructions XProcessingInstruction instruction = new XProcessingInstruction ("xml-stylesheet", "href=\" hello.css\ "type =\" text/css\ "); / / create declaration object XDeclaration xDeclaration = new XDeclaration (" 1.0", "GB2312", "yes"); / / create document type XDocumentType documentType = new XDocumentType ("Person", null, "Person.dtd", null) / / create XmlCData data XCData data = new XCData ("magical Liu Bei"); / / create XDocument document XDocument xDoc = new XDocument (); XElement xml = new XElement ("Persons", new XElement ("Person", new XAttribute ("Description", "the appearance of the dragon and Phoenix) ), new XElement ("Name", data), new XElement ("Age", "28"), new XElement ("Person", new XElement ("Name", "Guan Yu"), new XElement ("Age", "27")); xDoc.Add (documentType); xDoc.Add (instruction); xDoc.Declaration = xDeclaration XDoc.Add (xml); xDoc.Save (@ "D:\ 123.xml"); 3. Linq query generates XML
We instantiate a collection of book
Book [] books = new Book [] {new Book ("Ajax in Action", "Manning", 2005), new Book ("Windows Forms in Action", "Manning", 2006), new Book ("RSS and Atom in Action", "Manning", 2006)}
If we now want to create a collection of Year== 2006 in the following XML format
Manning Manning
Adopt linq mode
XElement xml = new XElement ("books", from book in books where book.Year = = 2006 select new XElement ("book", new XAttribute ("title", book.Title), new XElement ("publisher", book.Publisher); / / display this XMLConsole.WriteLine (xml)
Traditional way
XmlDocument doc = new XmlDocument (); XmlElement root = doc.CreateElement ("books"); foreach (Book book in books) {if (book.Year = = 2006) {XmlElement element = doc.CreateElement ("book"); element.SetAttribute ("title", book.Title); XmlElement publisher = doc.CreateElement ("publisher"); publisher.InnerText = book.Publisher; element.AppendChild (publisher); root.AppendChild (element);}} doc.AppendChild (root) / / display this XMLdoc.Save (Console.Out); 4. Attribute transfer out element
XML file:
Content
You can write some procedure code to create an element from an attribute, and then delete the attribute
Linq mode:
XElement root = XElement.Load ("Data.xml"); XElement newTree = new XElement ("Root", root.Element ("Child1"), from att in root.Attributes () select new XElement (att.Name, (string) att); xml.Save (@ "D:\ 123.xml")
Traditional way:
XElement root = XElement.Load ("Data.xml"); foreach (XAttribute att in root.Attributes ()) {root.Add (new XElement (att.Name, (string) att));} root.Attributes (). Remove (); 5. XmlDocument is converted to XDocumentXmlDocument doc = new XmlDocument (); doc.LoadXml (xmlStr); / / xml string is converted into xml document object XDocument xdoc = doc.ToXDocument (); / / xmldocument is converted into xdoccument extension method var eventId = xdoc.Document.Root.Element ("EventID") / / eventid node if (eventId! = null) {MessageBox.Show (eventId.Value); / / 15} under the root node
Expansion method
Public static class XmlDocumentExtensions {public static XDocument ToXDocument (this XmlDocument document) {return document.ToXDocument (LoadOptions.None);} public static XDocument ToXDocument (this XmlDocument document, LoadOptions options) {using (XmlNodeReader reader = new XmlNodeReader (document)) {return XDocument.Load (reader, options);}}. Output of XML data
XElement has a Save, which has multiple overloads and supports the input of XML data everywhere (file address, stream, TextWriter,XmlWriter).
XElement xml = new XElement ("Persons", new XElement ("Person", new XElement ("Name", "Liu Bei"), new XElement ("Age", "28")); / / 1, output to file xml.Save (@ "D:\ 123.xml"); / / 2, output to TextWriterTextWriter tw = new StringWriter () / / the second parameter SaveOptions enumeration supports formatting, indentation, keeping unimportant whitespace, removing duplicate namespaces xml.Save (tw, SaveOptions.None); Console.WriteLine (tw); / / 3, outputting to Streamusing (MemoryStream mem = new MemoryStream ()) {xml.Save (mem); Console.WriteLine (Encoding.UTF8.GetString (mem.ToArray ();} / / 4, outputting to XmlWriterXmlWriter xw = XmlWriter.Create (@ "D:\ LinqToXml.xml") Xml.Save (xw); xw.Flush (); 5. Query
Element (): gets the first child element of the current XML element with the specified name
Elements (): gets all the children of the current XML element, or all children with the specified name, and returns a collection of elements of type IEnumerable that can be queried by LINQ
Attribute (): gets the attribute of the current XML element with the specified name
Attributes (): gets all the attributes of the current XML element or attributes with the specified name, and returns the LINQ collection of type IEnumerable
1. Query the root element IEnumerable elements = from e in doc.Elements ("Products") select eTinct foreach (XElement e in elements) {Console.WriteLine ("{0}-{1}", e.Name, e.Value) 2. Query node var query = from p in doc.Element ("Products"). Elements ("Product") where (int) p.Element ("ProductID") = 1 orderby p.Attribute ("ID") .Value select p Query.ToList () .ForEach (item = > {Console.WriteLine ("{0}-{1}-{2}", item.Element ("ProductID") .Value, item.Element ("ProductName") .Value, item.Element ("UnitPrice") .value); 3. Query descendant nodes
The Descendants axis method is similar to the Elements type, except that Elements only looks for immediate child nodes under the current element, while Descendants traverses child elements at any level below the current element.
Var query = from b in root.Descendants ("Book") select BX foreach (var item in query) {Console.WriteLine (item.Element ("ProductName") .Value) 4. Query attribute var query = from p in xml.Nodes () .OfType () where (int) p.Attribute ("ID") .Value = = 1 select new {ID = p.Attribute ("ID") .Value, ProductID = p.Element ("ProductID") .Value ProductName = p.Element ("ProductName") .Value} 5. Fill in List:XElement root = XElement.Load (@ "like.xml"); var query = from ele in root.Elements ("book") select new {author = ele.Element ("author") .Value, price = ele.Element ("price") .Value}; String xml = null Foreach (var item in query) {xml = xml + item.ToString () + "\ n -\ n"; 6. Operation Node 1, add Node
Add (): adds content to the end of the child content of the XContainer.
AddFirst (): adds content at the beginning of the child content of the XContainer.
AddAfterSelf (): add content after XNode.
AddBeforeSelf (): add content before XNode.
XElement product = new XElement ("Product", new XAttribute ("ID", 2), new XElement ("ProductName", "LINQ to Object"), new XElement ("UnitPrice", 20m), new XElement ("Remark", ""); el.Add (product); 2. Modify and replace nodes
SetAttributeValue (): sets the value of the property. If the attribute does not exist, it is created. If the value is set to null, the property is removed.
SetElementValue (): sets the value of the child element. If the element does not exist, it is created. If the value is set to null, the element is removed.
Value: replaces the contents (child nodes) of the element with the specified text.
SetValue (): sets the value of the element.
ReplaceAll (): replaces all the contents of the element (child nodes and attributes).
ReplaceAttributes (): replaces the attribute of the element.
ReplaceWith (): replaces the node with new content.
ReplaceNodes (): replaces child nodes with new content.
IEnumerable products = from e in el.Elements ("Product") where e.Attribute ("ID"). Value = = "1" select eigenif (products.Count () > 0) {XElement product = products.First (); product.SetAttributeValue ("ID", 3) Product.ReplaceNodes (new XElement ("ProductName", "LINQ to XML Version 2"), new XElement ("UnitPrice", 30));} 3. Delete node
RemoveAll (): removes all the contents (child nodes and attributes) of the element.
RemoveAttributes (): removes attributes from an element.
ReplaceNodes (): deletes the child node.
Remove (): removes the entire node or node collection
IEnumerable products = from e in el.Elements ("Product") where e.Attribute ("ID"). Value = = "2" select escape if (products.Count () > 0) {products.First (). Remove ();} xml.Element ("Product"). Remove (); / delete the first produce child element xml.Elements ("Product"). Remove () / delete all production child elements xml.SetElementValue ("Product", null); / delete the first production child element xml.Element ("Product"). SetElementValue ("ProductID", 1); / modify the production ID child element xml.Element ("Product"). SetElementValue ("ProductID", null); / / delete production subelement 4, attribute operation / / add attributes: product.Add ("ID", 1) / / modify attributes: product.SetAttributeValue ("ID", 2); / / delete attributes: product.Attribute ("ID"). Remove (); VI. Query using XPath
In order to use XPath queries in LINQ XML, you need to add the System.Xml.XPath namespace. As follows:
Using Sytem.Xml.XPath
With the addition of the System.Xml.XPath namespace, the XNode class adds a series of extension methods. With these extension methods, we have two options for dealing with XML. So that our application can carry out a smooth migration.
The CreateNavigator method, which allows us to create a XPathNavigator object from an existing XNode object.
The XPathEvaluate method allows XPath expressions on XNode to be evaluated.
The XPathSelectElement method returns the first element that matches the expression, and the XPathSelectElements method returns all elements that match the expression.
To query the following XML data:
CLR via C# Essential .NET Refactoring Domain Driven Design Patterns of Enterprise Application Architecture Extreme Programming Explained Pragmatic Unit Testing with C# Head First Design Patterns
How to use XPath to query XML data:
XElement root = XElement.Load ("categorizedBooks.xml"); var books = from book in root.XPathSelectElements ("/ / book") select book;foreach (XElement book in books) {Console.WriteLine ((string) book);} VII. XML for conversion 1. Conversion using XSLT string xsl = @ "http://www.w3.org/1999/XSL/Transform'>Book Catalog by,"; XElement books = XElement.Load ("books.xml"); XDocument output = new XDocument () Using (XmlWriter writer = output.CreateWriter ()) {XslCompiledTransform xslTransformer = new XslCompiledTransform (); xslTransformer.Load (XmlReader.Create (new StringReader (xsl); xslTransformer.Transform (books.CreateReader (), writer);} Console.WriteLine (output)
In order to reuse the transformation code, the transformation logic can be encapsulated in an extension method
Public static class XmlExtensions {public static XDocument XslTransform (this XNode node, string xsl) {XDocument output = new XDocument (); using (XmlWriter writer = output.CreateWriter ()) {XslCompiledTransform xslTransformer = new XslCompiledTransform (); xslTransformer.Load (XmlReader.Create (new StringReader (xsl); xslTransformer.Transform (node.CreateReader (), writer);} return output }} / / use this extension method XElement.Load ("books.xml") .XslTransform (xsl); 2. Use LINQ to XML to transform XML
XSL is not the only way to change the XML format (it was the only practical way in the past), but today, LINQ to XML offers a competitive option. To use LINQ to XML for transformation, you need an LINQ expression that uses projection. The trick is that the projection must return a XElement instead of an anonymous type.
String xmlFile = Server.MapPath ("DvdList.xml"); XDocument doc = XDocument.Load (xmlFile) XDocument newDoc = new XDocument (new XDeclaration, "utf-8", "yes"), new XElement ("Movies", from DVD in doc.Descendants ("DVD") where (int) DVD.Attribute ("ID") < 3 select new XElement [] {new XElement ("Moive", new XAttribute ("name", (string) DVD.Element ("Title")) DVD.Descendants ("Star")}) String newFile = Server.MapPath ("MovieList.xml"); newDoc.Save (newFile)
Results:
Keanu Reeves Laurence Fishburne Tom Hanks Robin Wright
Syntax based on LINQ transformations is generally easier to understand and more accurate than transformations that use XSL stylesheets. You can also easily replace it with another collection of IEnumable, including the result set obtained by LINQ to Entities, and then optionally package it into a XML document in another format.
Thank you for your reading, the above is the content of "how to generate XML elements or XML documents in C#". After the study of this article, I believe you have a deeper understanding of how to generate XML elements or XML documents in C#. The specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.