. Net read/write xml document details

Source: Internet
Author: User
Tags baseuri net xml
This article mainly introduces the example of. net reading and writing xml documents. For more information, see the example of. net reading and writing xml documents. For more information, see

1. XML-related namespaces in the. Net Framework

System. Xml
It contains some classes related to the read/write operations of XML documents, including XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, XmlTextWriter, and XmlNode. its sub-classes include: xmlDocument, XmlDataDocument, XmlDocumentFragment) and other classes.

System. Xml. Schema
Contains classes related to the XML Schema, including XmlSchema, XmlSchemaAll, XmlSchemaXPath, and XmlSchemaType.

System. Xml. Serialization
Contains classes related to the serialization and deserialization operations of XML documents.
Serialization: converts XML-format data into stream-format data and can be transmitted over the network;
Deserialization: opposite operations are completed to restore data in the stream format to XML format.

System. Xml. Xpath
Including XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. these classes can complete the navigation of XML documents.
(With the help of the XPathDocument class, the XPathNavigator class can complete the quick XML document navigation function. this class provides programmers with many Move methods to complete the navigation function .)

System. Xml. Xsl
Converts XSLT.

Method 2 for writing XML documents

Use the XmlWriter class to implement write operations. this class contains the methods and attributes required for writing XML documents. it is the base class of the XmlTextWriter class and XmlNodeWriter class.

Some 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 describes how to write an XML document by using its subclass XmlTextWriter.

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

After the object is created, we call the WriterStartDocument method to write the XML document;
After writing, call WriteEndDocument to end the writing process and call the Close method to Close it.

During the write process, we can:
Call the WriteComment method to add instructions;
Call the WriteString method to add a string;
Add an element by calling the WriteStartElement and WriteEndElement methods;
Call the WriteStartAttribute and WriteEndAttribute methods to add an attribute;
Call the WriteNode method to add an entire node;
Other write methods include WriteProcessingInstruction and WriteDocType.

The following example describes how to use these methods to write XML documents.

The code is as follows:

Using System; using System. xml; namespace WriteXML {class Class1 {static void Main (string [] args) {try {// create XmlTextWriter class instance object XmlTextWriter textWriter = new XmlTextWriter ("C: \ w3sky. xml ", null); textWriter. formatting = Formatting. indented; // start the write process and call the WriteStartDocument method textWriter. writeStartDocument (); // write description 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 (); // end of writing a document. call the WriteEndDocument method textWriter. writeEndDocument (); // disable textWriter. close ();} catch (System. exception e) {Console. writeLine (e. toString ());}}}}

Three methods for reading XML documents

Use the XmlTextReader class object to read the XML document. Specify the location of the XML file in the constructor of the created object.

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

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

XmlNodeType contains XML items such as XmlDeclaration, Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, and WhiteSpace.

The following example shows how to read the created object from the "books. xml" file and obtain relevant information through the attributes of the xml object, such as Name, BaseURI, Depth, and LineNumber. The information is displayed on the console. (Use the "books. xml" file attached to 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 the XmlTextReader class and call the Read method to Read the XML file XmlTextReader textReader = new XmlTextReader ("C: \ books. xml "); textReader. read (); // if the node is not empty, the loop body while (textReader. read () {// Read the first element textReader. moveToElement (); Console. writeLine ("XmlTextReader Properties Test"); Console. writeLine ("======================"); // read the attributes of this element and display them on the Console. writeLine ("Name:" + textReader. name); Console. writeLine ("Base URI:" + textReader. baseURI); Console. writeLine ("Local Name:" + textReader. localName); Console. writeLine ("Attribute Count:" + textReader. attributeCount. toString (); Console. writeLine ("Depth:" + textReader. depth. toString (); Console. writeLine ("Line Number:" + textReader. lineNumber. toString (); Console. writeLine ("Node Type:" + textReader. nodeType. toString (); Console. writeLine ("Attribute Count:" + textReader. value. toString ());}}}}

4. use the XmlDocument class

The XmlDocument class represents an XML document. it can complete all types of operations related to the entire XML document, and its XmlDataDocument class is also very important and worthy of in-depth research. This class contains Load, LoadXml, Save, and other important methods.

Load method: you can import XML data from an XML file specified by a string, a stream object, a TextReader object, and an XmlReader object.
LoadXml method: imports XML data from a specific XML file.
Save method: Save the XML data to an XML file, a stream object, a TextWriter object, and an XmlWriter object.

In the following example, the LoadXml method of the XmlDocument class object is used. it reads XML data from an XML document segment and calls its Save method to Save the data in a file.

The code is as follows:

// Create an XmlDocument class object XmlDocument doc = new XmlDocument (); doc. LoadXml (("
 
  
   
Tommy Lex
  
 "); // Save it to the file doc. save ("C: \ student. xml "); // You can also display XML data in the console by changing the parameters in the Save method. the method is as follows: doc. save (Console. in the following example, an XmlTextReader object is used to read "books. xml data in the XML file. Create an XmlDocument object and load the XmlTextReader object, so that the XML data is read to the XmlDocument object. Finally, the XML data is displayed on the console using the Save method of the object. XmlDocument doc = new XmlDocument (); // Create an XmlTextReader object to read XML data XmlTextReader reader = new XmlTextReader ("c: \ books. xml "); reader. read (); // loads the object doc of the XmlTextReader class. load (reader); // Display 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. net xml file operations

The code is as follows:

// Set the physical path of the configuration file public string xmlPath = "/manage/spider/config. xml"; protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {// sets the physical path of the program + string path of the file = Request. physicalApplicationPath + xmlPath; // Obtain the XML element object XElement config = XElement. load (path); if (config! = Null) {// Obtain the node child element XElement eleAmazonDetailUrl = config. element ("AmazonDetailUrl"); XElement eleAmazonListUrl = config. element ("AmazonListUrl"); XElement eleHz = config. element ("Hz"); XElement eleCount = config. element ("Count"); // present the obtained data on the page if (eleAmazonDetailUrl! = Null) TextBox_AmazonDetailUrl.Text = eleAmazonDetailUrl. Value; if (eleAmazonListUrl! = Null) TextBox_AmazonListUrl.Text = eleAmazonListUrl. Value; if (eleHz! = Null) TextBox_Hz.Text = eleHz. Value; 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 the 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 the element to the root of the XML file in the specified path. save (path );}

The above is the detailed description of the. net read/write xml document. For more information, see other related articles in the first PHP community!

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.