. Net read/write xml document details

Source: Internet
Author: User
Tags baseuri net xml

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.

Copy codeThe 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 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 ();

// When the document writing ends, call the WriteEndDocument method.
TextWriter. WriteEndDocument ();

// Disable textWriter
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)
Copy codeThe Code is as follows:
Using System;
Using System. Xml;

Namespace ReadXml
{
Class Class1
{
Static void Main (string [] args)
{
// Create an XmlTextReader Class Object and call the Read method to Read the XML file
XmlTextReader textReader = new XmlTextReader ("C: \ books. xml ");
TextReader. Read ();
// Execute the loop body if the node is not empty
While (textReader. Read ())
{
// Read the first element
TextReader. MoveToElement ();
Console. WriteLine ("XmlTextReader Properties Test ");
Console. WriteLine ("========================= ");

// Read the attributes of the element and display it on the console
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.

Copy codeThe Code is as follows:
// Create an object of the XmlDocument class
XmlDocument doc = new XmlDocument ();
Doc. LoadXml ("<Student type = 'regular' Section = 'B'> <Name> Tommy Lex </Name> </Student> "));

// 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. Out );

In the following example, an XmlTextReader object is used to read the xml data in the "books. 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 ();

// Load the object of the XmlTextReader class
Doc. Load (reader );
// Display XML data in the console
Doc. Save (Console. Out );

Xml file
Copy codeThe Code is as follows:
<? Xml version = '1. 0'?>
<! -- This file represents a fragment of a book store inventory database -->
<Bookstore>
<Book genre = "autobiography" publicationdate = "1981" ISBN = "1-861003-11-0">
<Title> The Autobiography of Benjamin Franklin </title>
<Author>
<First-name> Benjamin </first-name>
<Last-name> Franklin </last-name>
</Author>
<Price> 8.99 </price>
</Book>
<Book genre = "novel" publicationdate = "1967" ISBN = "0-201-63361-2">
<Title> The Confidence Man </title>
<Author>
<First-name> Herman </first-name>
<Last-name> Melville </last-name>
</Author>
<Price> 11.99 </price>
</Book>
<Book genre = "philosophy" publicationdate = "1991" ISBN = "1-861001-57-6">
<Title> The Gorgias </title>
<Author>
<First-name> Sidas </first-name>
<Last-name> Plato </last-name>
</Author>
<Price> 9.99 </price>
</Book>
</Bookstore>

Another example of. net xml file operations

Copy codeThe 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)
{
// Set the physical path of the program + the physical path of the file
String path = 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 XML file in the specified path
Root. Save (path );
}

Related Article

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.