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

.net how to read and write xml documents

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail about. Net how to read and write xml documents. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

1. XML-related namespaces in the net framework

System.Xml

Contains some classes related to the read and write operations of XML documents, they are: XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, XmlTextWriter and XmlNode (its subclasses include: XmlDocument, XmlDataDocument, XmlDocumentFragment) and so on.

System.Xml.Schema

Contains classes related to the XML schema, including XmlSchema, XmlSchemaAll, XmlSchemaXPath, and XmlSchemaType classes.

System.Xml.Serialization

Contains classes related to serialization and deserialization of XML documents.

Serialization: data in XML format is converted into data in stream format and can be transmitted over the network

Deserialization: do the opposite, that is, restore data in stream format to data in XML format.

System.Xml.Xpath

Contains XPathDocument, XPathExression, XPathNavigator, XPathNodeIterator and other classes, these classes can complete the navigation of XML documents.

With the help of the XPathDocument class, the XPathNavigator class can complete the fast XML document navigation function, which provides programmers with many Move methods to complete the navigation function. )

System.Xml.Xsl

Complete the conversion function of XSLT.

The method of writing XML documents

Write operations are implemented with the XmlWriter class, which contains the methods and properties needed to write the XML document, which is the base class for the XmlTextWriter class and the XmlNodeWriter class.

Some methods of write operations appear in pairs, for example, if you want to write an element, first call the WriteStartElement method-> write the actual content-> call the WriteEndElement method to end.

The following shows how to write an XML document through its subclass XmlTextWriter.

XmlTextWriter textWriter = New XmlTextWriter ("C:\\ myXmFile.xml", null)

After creating the object, we call the WriterStartDocument method to start writing the XML document

When the writing is finished, the WriteEndDocument is called to end the writing process, and the Close method is called to close it.

In the process of writing, we can:

Call the WriteComment method to add a description

Add a string by calling the WriteString method

Add an element by calling the WriteStartElement and WriteEndElement method pairs

Add an attribute by calling the WriteStartAttribute and WriteEndAttribute method pairs

Add an entire node by calling the WriteNode method

Other writing methods include WriteProcessingInstruction, WriteDocType and so on.

The following example shows how to use these methods to write an XML document.

The code is as follows:

Using System;using System.Xml; namespace WriteXML {class Class1 {static void Main (string [] args) {try {/ / create an instance object of the XmlTextWriter class XmlTextWriter textWriter = new XmlTextWriter ("C:\\ w3sky.xml", null); textWriter.Formatting = Formatting.Indented; / / start the writing process and call the WriteStartDocument method textWriter.WriteStartDocument (); / / write instructions textWriter.WriteComment ("First Comment XmlTextWriter Sample Example") TextWriter.WriteComment ("w3sky.xml in root dir"); / / create a node textWriter.WriteStartElement ("Administrator"); textWriter.WriteElementString ("Name", "formble"); textWriter.WriteElementString ("site", "w3sky.com"); textWriter.WriteEndElement (); / / finish writing the document, call the WriteEndDocument method textWriter.WriteEndDocument (); / / close textWriter textWriter.Close () } catch (System.Exception e) {Console.WriteLine (e.ToString ());}

The method of reading XML documents for three times

Use the object of the XmlTextReader class to read the XML document. You can specify the location of the XML file in the constructor that creates the new object.

XmlTextReader textReader = new XmlTextReader ("C:\\ books.xml")

The attribute NodeType in the XmlTextReader class can know the node type of its node. By comparing with the elements in the enumerated type XmlNodeType, you can get the node type of the corresponding node and perform related operations on it.

The enumerated type XmlNodeType contains types of XML items such as XmlDeclaration, Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, and WhiteSpace.

The following example creates an object by reading the "books.xml" file, obtains the relevant information through the Name, BaseURI, Depth, LineNumber, and other properties of the xml object, and displays it in the console. (use the "books.xml" file included with the VS.net development tool as an example)

The code is as follows:

Using System;using System.Xml; namespace ReadXml {class Class1 {static void Main (string [] args) {/ / create an object of XmlTextReader class and call the Read method to read the XML file XmlTextReader textReader = new XmlTextReader ("C:\\ books.xml"); textReader.Read () / / execute the loop body while (textReader.Read ()) {/ / read the first element textReader.MoveToElement (); Console.WriteLine ("XmlTextReader Properties Test"); Console.WriteLine ("=") if the node is not empty / / read the attributes of the element and display them in the console Console.WriteLine ("Name:" + textReader.Name); Console.WriteLine ("BaseURI:" + textReader.BaseURI); Console.WriteLine ("LocalName:" + textReader.LocalName); Console.WriteLine ("AttributeCount:" + textReader.AttributeCount.ToString ()) Console.WriteLine ("Depth:" + textReader.Depth.ToString ()); Console.WriteLine ("LineNumber:" + textReader.LineNumber.ToString ()); Console.WriteLine ("NodeType:" + textReader.NodeType.ToString ()); Console.WriteLine ("Attribute Count:" + textReader.Value.ToString ());}

Fourth, use XmlDocument class.

The XmlDocument class represents the XML document, which can complete all kinds of operations related to the whole XML document. At the same time, the XmlDataDocument class related to it is also very important and worthy of in-depth study. This class contains important methods such as Load, LoadXml, and Save.

Load method: you can import XML data from a XML file specified by a string or from a stream object, a TextReader object, or a XmlReader object.

LoadXml method: completes the function of importing XML data from a specific XML file.

Save method: save the XML data to a XML file or to a stream object, a TextWriter object, or a XmlWriter object.

In the following example, you use the LoadXml method of the XmlDocument class object, which reads XML data from a XML document segment and calls its Save method to save the data in a file.

The code is as follows:

/ / create an object of XmlDocument class XmlDocument doc = new XmlDocument (); doc.LoadXml (("Tommy Lex")); / / Save to the file doc.Save ("C:\\ student.xml"); / / you can also display the XML data in the console by changing the parameters in the Save method as follows: doc.Save (Console.Out) In the following example, a XmlTextReader object is used to read XML data from the "books.xml" file. Then create a XmlDocument object and load the XmlTextReader object so that the XML data is read into the XmlDocument object. Finally, the XML data is displayed in the console through the object's Save method. XmlDocument doc = new XmlDocument (); / / create a XmlTextReader object, read the XML data XmlTextReader reader = new XmlTextReader ("c:\\ books.xml"); reader.Read (); / load the object doc.Load (reader) of the XmlTextReader class; / / display the XML data in the console doc.Save (Console.Out)

Xml file

The code is as follows:

The Autobiography of Benjamin Franklin Benjamin Franklin 8.99 The Confidence Man Herman Melville 11.99 The Gorgias Sidas Plato 9.99

Another example of a .net operation xml file

The code is as follows:

/ / set configuration file physical path public string xmlPath = "/ manage/spider/config.xml"; protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {/ / set program physical path + file physical path string path = Request.PhysicalApplicationPath + xmlPath; / / get XML element object XElement config = XElement.Load (path) If (config! = null) {/ / get node child elements XElement eleAmazonDetailUrl = config.Element ("AmazonDetailUrl"); XElement eleAmazonListUrl = config.Element ("AmazonListUrl"); XElement eleHz = config.Element ("Hz"); XElement eleCount = config.Element ("Count") / / render the fetched data if (eleAmazonDetailUrl! = null) TextBox_AmazonDetailUrl.Text = eleAmazonDetailUrl.Value; if (eleAmazonListUrl! = null) TextBox_AmazonListUrl.Text = eleAmazonListUrl.Value; if (eleHz! = null) TextBox_Hz.Text = eleHz.Value on the page If (eleCount! = null) TextBox_Count.Text = eleCount.Value;} else Response.Write ("");}} protected void btn_Save_Click (object sender, EventArgs e) {/ / set the XML file path string path = Request.PhysicalApplicationPath + xmlPath / / set node name and content XElement root = new XElement ("Settings", new XElement ("AmazonDetailUrl", TextBox_AmazonDetailUrl.Text.Trim ()), new XElement ("AmazonListUrl", TextBox_AmazonListUrl.Text.Trim ()), new XElement ("Hz", TextBox_Hz.Text.Trim ()), new XElement ("Count") TextBox_Count.Text.Trim ()) / serialize elements to the specified path of the XML file root.Save (path);} on ".net how to read and write xml documents" this article is shared here, 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, please share it out 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