Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read and write XML files

Shulou Source: shulou.com Published: 2022-06-03 12:07:23 11月15日 Update

This article mainly shows you "how to read and write XML files", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to read and write XML files" this article.

Here we first introduce two objects that manipulate XML files: XmlTextReader and XmlTextWriter

The object used to open and read Xml files is the XmlTextReader object. The following example opens an example file, sample.xml, in the same path as the program

XmlTextReader reader = new XmlTextReader ("sample.xml")

Then we can use its Read method to automatically facilitate XML files. Example:

While (reader.Read ()) {/ / fill in the operation code for XML here}

Let's look at a more complicated example.

While (reader.Read ()) 2 {3 switch (reader.NodeType) 4 {5 case XmlNodeType.Element: / / the current node is an element 6 Console.Write (""); 10 break;11 case XmlNodeType.DocumentType: / / XML file type declaration 12 Console.WriteLine (reader.NodeType + "" + reader.Value); 13 break;14... 15} 16}

Starting from line 3, we judge the type of node according to the NodeType attribute, and deal with it differently according to the type of node.

The following table lists some common node types.

The value of NodeType of XmlTextReader

Types

Description

All

All nodes

Attribute

An attribute

CDATA

Escape text that will be treated as a markup language, such as HTML

Comment

Use delimited comments

Document

The root node of the XML data tree

DocumentType

Type declaration of the document, that is, the tag

Element

An element, usually the actual data in a XML file

EndTag

The end position of the element

None

Not a node.

Text

Returns the text content of the element

XMLDeclaration

XML declaration node, such as

Tags: File element node content type attribute method comment character data closure example object common use flag article processing different string quotation mark Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Huawei vpn OPPO Reno Apple