Home Backend Development XML/RSS Tutorial Detailed code examples for interpreting and writing XML files

Detailed code examples for interpreting and writing XML files

Mar 23, 2017 pm 04:41 PM

This article will cover 3 aspects:
1. Accessing XML files
2. XML Document Object Model
3. XML and DataSet

Here we first introduce two objects for operating XML files: XmlTextReader and XmlTextWriter
The object used to open and read Xml files is the XmlTextReader object. The following example opens a sample file sample.xml

XmlTextReader reader = new XmlTextReader("sample.xml");
Copy after login

in the same path as the program. Then we can automatically facilitate the XML file through its Read method. Example:

while(reader.Read())
{
       //在这里填写对于XML的操作代码
}
Copy after login

Let’s look at a more complicated example.

while(reader.Read())
 2{
 3    switch(reader.NodeType)
 4    {
 5        case XmlNodeType.Element:   //当前节点是一个元素
 6              Console.Write("<" + reader.Name);
 7            while(reader.MoveToNextAttribute()) //按照顺序读取下一个属性
 8              Console.Write(" " + reader.Name + "=&#39;" + reader.Value + "&#39;");
 9            Console.Write(">");
10            break;
11        case XmlNodeType.DocumentType:  //XML文件的类型声明
12              Console.WriteLine(reader.NodeType + "<" + reader.Name + ">" + reader.Value);
13            break;
14        ……
15        }
16    }
Copy after login

Starting from line 3, we judge the type of node based on the NodeType attribute, and perform different processing according to different types of nodes.

The following table lists some commonly used node types.

## An attributeCDATAEscape text that would be treated as a markup language (such as HTML)Comment##Comments separated by DocumentDocumentType##ElementEndTagNone

##XmlTextReaderThe value of NodeType

Type

Description

All

All nodes

Attribute

The root node of the XML data tree

The type declaration of the document, that is, tag

An element, usually the actual data in the XML file

The end position of the element

## is not a node

Text
Returns the text content of the element

XMLDeclaration
XML declaration node, for example

在进行写入XML文件时我们使用的XmlTextWriter类,它是XmlWriter的子类,速度快且不使用缓存,但是同XmlTextReader一样,在写入XML文件时只能向前。

我们假定要写入的XML文件在C盘根目录下:

XmlTextWriter writer = new XmlTextWriter("C:\\sample2.xml",null);
Copy after login

在这里如果不想把数据写入文件,而只是想在命令窗口显示,则可以把“Console.Out”作为参数传递给构造器,此时应把上述语句改为:

XmlTextWriter writer = new XmlTextWriter(Console.Out);
Copy after login

下面我们介绍一下写入XML文件数据的一些常用方法:

XmlTextWriter的常用方法

方法

说明

用法

WriteStartDocument

写XML声明部分,即“

writer.WriteStartDocument();

WriteEndDocument

使没有闭合元素闭合

writer.WriteEndDocument();

WriteDocType

写DOCTYPE声明

writer.WriteDocType("sample2",null,null,"");

WriteStartElement

写元素的开始标志

writer.WriteStartElement("sample2");

WriteEndElement

写元素的结束标志

writer.WriteEndElement();

WriteString

写入字符串

writer.WriteString("Pride And Prejudice");

WriteCData

写CDATA块,即写入的文字在

writer.WriteCData("Price 15% off!!");

WriteRaw

手工写入一行,不作任何处理

writer.WriteRaw("this & that");

WriteEntityRef

写入实体引用,即前面加“&”后面加“;”

writer.WriteEntityRef("h");

WriteProcessingInstruction

写入处理指令,即前面加“

writer.WriteProcessingInstruction("xml-stylesheet",PItext);

WriteComment

写入注释,自动加入注释标志“

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the xml file for? What is the xml file for? Aug 03, 2023 am 09:38 AM

XML files are a markup language used to describe and transmit data. It is known for its scalability, readability, and flexibility and is widely used in web applications, data exchange, and web services. The format and structure of XML make the organization and interpretation of data simple and clear, thereby improving the efficiency of data exchange and sharing.

xml file opening method xml file opening method Feb 22, 2024 pm 04:04 PM

Common XML file opening methods: 1. Text editor; 2. Browser; 3. XML editor; 4. Integrated development environment; 5. Microsoft Excel, etc.

How to use PHP to implement data caching, reading and writing functions How to use PHP to implement data caching, reading and writing functions Sep 05, 2023 pm 05:45 PM

How to use PHP to implement data caching and read-write functions. Caching is an important way to improve system performance. Through caching, frequently used data can be stored in memory to increase the reading speed of data. In PHP, we can use various methods to implement data caching and reading and writing functions. This article will introduce two common methods: using file caching and using memory caching. 1. Use file caching. File caching stores data in files for subsequent reading. The following is a sample code that uses file caching to read and write data:

Practical combat: hard disk io read and write test on Linux Practical combat: hard disk io read and write test on Linux Feb 19, 2024 pm 03:40 PM

Concept fio, also known as FlexibleIOTester, is an application written by JensAxboe. Jens is the maintainer of blockIOsubsystem in LinuxKernel. FIO is a tool used to test network file system and disk performance. It is often used to verify machine models and compare file system performance. It automatically sends fio commands to a list of cluster machines and collects IOPS for small files and throughput data for large files. rw=[mode]rwmixwrite=30 In mixed read and write mode, writing accounts for 30% moderead sequential read write sequential write readwrite sequential mixed read and write randwrite random write r

Revealing the inner workings of Java file operations Revealing the inner workings of Java file operations Feb 28, 2024 am 08:22 AM

File System APIThe internal principles of Java file operations are closely related to the file system API of the operating system. In Java, file operations are provided by the java.nio.file module in the java.NIO package. This module provides an encapsulation of the file system API, allowing Java developers to use a unified API to perform file operations on different operating systems. File Object When a Java program needs to access a file, it first needs to create a java.nio.file.Path object. The Path object represents a path in the file system, which can be an absolute path or a relative path. Once the Path object is created, you can use it to get various properties of the file, such as the name

What is xml file What is xml file Jan 04, 2021 am 10:59 AM

XML files generally refer to files with extensible markup language written in them. XML is extensible markup language, a subset of standard universal markup language. It is a markup language used to mark electronic documents to make them structural.

Decrypt the reading and writing methods of processing DBF files in Java Decrypt the reading and writing methods of processing DBF files in Java Mar 29, 2024 pm 12:39 PM

Decrypting the reading and writing methods of processing DBF files in Java DBF (dBaseFile) is a common database file format that is usually used to store tabular data. In Java programs, processing the reading and writing of DBF files is a relatively common requirement. This article will introduce how to use Java to decrypt this process and provide specific code examples. 1. Reading DBF files In Java, reading DBF files usually requires the use of third-party libraries, such as the dbfread library. First, you need to configure the project

How to deal with concurrent reading and writing data consistency issues in Java development How to deal with concurrent reading and writing data consistency issues in Java development Jun 29, 2023 am 08:10 AM

In Java development, it is very important to deal with the issue of concurrent read and write data consistency. With the popularity of multi-threaded and distributed systems, simultaneous reading and writing of data is becoming more and more common, and if not handled carefully, it may lead to data inconsistency. This article will introduce several common methods to deal with concurrent read and write data consistency issues. 1. Use lock mechanism One of the most commonly used methods to deal with concurrent read and write data consistency issues is to use a lock mechanism (such as the synchronized keyword or the ReentrantLock class). Pass

See all articles