. NET read and write XML document details _ Practical skills

Source: Internet
Author: User
Tags baseuri serialization

One. XML-related namespaces in the NET Framework

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

System.Xml.Schema
Contains classes related to XML schemas, which include classes such as XmlSchema, Xmlschemaall, Xmlschemaxpath, and XmlSchemaType.

System.Xml.Serialization
Contains classes related to serialization and deserialization operations of XML documents.
Serialization: Converts XML-formatted data into stream-formatted data and can be transmitted over the network;
Deserialization: Completes the reverse operation and restores the data in the stream format to the data in XML format.

System.Xml.Xpath
Includes classes such as XPathDocument, Xpathexression, XPathNavigator, and XPathNodeIterator, which can complete the navigation functions of XML documents.
(with the help of the XPathDocument class, the XPathNavigator class can perform fast XML document navigation, which provides programmers with a number of move methods to complete the navigation function.) )

System.Xml.Xsl
Completes the XSLT conversion function.

Two ways to write XML documents

Write with the XmlWriter class, which contains the methods and attributes required to write an XML document, which is the base class for the XmlTextWriter class and the XmlNodeWriter class.

Some methods of writing are in pairs, such as you write an element, first call the WriteStartElement method-> write the actual content-> Call WriteEndElement method end.

The following subclass XmlTextWriter describes how to write XML documents.

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

After creating the object, we call the Writerstartdocument method to start writing the XML document;
When you finish writing, call WriteEndDocument to end the write process and call the Close method to turn it off.

In the process of writing, we can:
Call the WriteComment method to add the description;
To add a string by calling the WriteString method;
Add an element by invoking the WriteStartElement and writeendelement method pairs;
Add an attribute by invoking the WriteStartAttribute and WriteEndAttribute method pairs;
Add an integer node by calling the WriteNode method;
Other ways of writing include WriteProcessingInstruction and Writedoctype, among others.

The following example demonstrates how to use these methods to complete the writing of an XML document.

Copy Code code as follows:

Using System;
Using System.Xml;

Namespace WriteXml
{
Class Class1
{
static void Main (string[] args)
{
Try
{
To 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 invoke the WriteStartDocument method
Textwriter.writestartdocument ();

Write description
Textwriter.writecomment ("The 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 ();

Write document end, call WriteEndDocument method
Textwriter.writeenddocument ();

Close TextWriter
Textwriter.close ();
}
catch (System.Exception e)
{
Console.WriteLine (E.tostring ());
}
}

}
}

Three ways to read XML documents

Reads the XML document with the object of the XmlTextReader class. Specify the location of the XML file in the constructor that creates the new object.

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

A property in the XmlTextReader class NodeType can know the node type of its node. By comparing the elements in the enumeration type XmlNodeType, you can get the node types of the corresponding nodes and complete the associated operations.

Enumeration type XmlNodeType contains such things as XmlDeclaration, Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, Processinstruction and the types of XML items such as whitespace.

The following example creates an object by reading the "books.xml" file, obtains the relevant information through the properties of the XML object's name, BaseURI, Depth, linenumber, and displays it in the console. (Use the "books.xml" file included with the Vs.net development tool as an example)

Copy Code code 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 ();
Execute loop Body if 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 in 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 ());
}
}
}
}

Four uses XmlDocument class

The XmlDocument class represents an XML document that can complete all kinds of operations related to the entire XML document, and it is also important to XmlDataDocument classes that are related to it, and deserve further study. This class contains important methods such as load, Loadxml, and save.

Load method: You can import XML data from an XML file that you specify from a string or from a stream object, a TextReader object, and a XmlReader object.
Loadxml Method: Completes the ability to import XML data from a specific XML file.
Save method: Saves the XML data to an XML file or to a Stream object, a TextWriter object, a XmlWriter object.

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

Copy Code code as follows:

Create an object for a XmlDocument class
XmlDocument doc = new XmlDocument ();
Doc. Loadxml ("<student type= ' regular ' section= ' B ' ><name>tommy lex</name></student>"));

Save to 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 the XML data in the "books.xml" file. It then creates a XmlDocument object and loads the XmlTextReader object so that the XML data is read into the XmlDocument object. Finally, the XML data is displayed in the console using the object's Save method.

XmlDocument doc = new XmlDocument ();
Create a XmlTextReader object to read XML data
XmlTextReader reader = new XmlTextReader ("C:\\books.xml");
Reader. Read ();

Loading an object of the XmlTextReader class
Doc. Load (reader);
To display XML data in the console
Doc. Save (Console.Out);

XML file

Copy Code code as follows:

<?xml version= ' 1.0 '?>
<!--This file represents a fragment of the 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>

An example of another. NET Operations XML file

Copy Code code as follows:

To set the physical path of a configuration file
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 the node idea element
XElement eleamazondetailurl = config. Element ("Amazondetailurl");
XElement eleamazonlisturl = config. Element ("Amazonlisturl");
XElement elehz = config. Element ("Hz");
XElement elecount = config. Element ("Count");
To render the data that is fetched 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)
{
To set the XML file path
String path = Request.physicalapplicationpath + Xmlpath;
To set the name and content of a node
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 ())
);
Serializes an element into an XML file of a specified path
Root. Save (path);
}

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.