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

How to understand. Net reading and writing xml documents

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

Share

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

This article introduces the relevant knowledge of "how to understand. Net reading and writing xml documents". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

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 copy 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 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 ()

/ / after 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 copy 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 ()

/ / 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 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 copy code is as follows:

/ / create an object of the XmlDocument class

XmlDocument doc = new XmlDocument ()

Doc.LoadXml (("Tommy Lex"))

/ / Save to a file

Doc.Save ("C:\\ student.xml")

/ / you can also display 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 to read XML data

XmlTextReader reader = new XmlTextReader ("c:\\ books.xml")

Reader.Read ()

/ / load objects of the XmlTextReader class

Doc.Load (reader)

/ / display XML data in the console

Doc.Save (Console.Out)

Xml file

The copy 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 copy 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 program physical path + file physical path

String path = Request.PhysicalApplicationPath + xmlPath

/ / get the XML element object

XElement config = XElement.Load (path)

If (config! = null)

{

/ / get node sub-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 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 name and content of the 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 ())

);

/ / serialize the element to the XML file of the specified path

Root.Save (path)

}

This is the end of the introduction of "how to understand. Net read and write xml documents". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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