Home  >  Article  >  Backend Development  >  Detailed code examples for interpreting and writing XML files

Detailed code examples for interpreting and writing XML files

黄舟
黄舟Original
2017-03-23 16:41:562045browse

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");

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

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

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    }

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 c629567a66d32afc479b9ce2f0d8aaecDocumentDocumentType##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, 1d4c3cf0a242d7a29a1ff1d6757e7409 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 7c48bae358e23fcf3d27411460b5c8ae”

writer.WriteStartDocument();

WriteEndDocument

使没有闭合元素闭合

writer.WriteEndDocument();

WriteDocType

写DOCTYPE声明

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

WriteStartElement

写元素的开始标志

writer.WriteStartElement("sample2");

WriteEndElement

写元素的结束标志

writer.WriteEndElement();

WriteString

写入字符串

writer.WriteString("Pride And Prejudice");

WriteCData

写CDATA块,即写入的文字在2963dcafef8686bc91e578183ecdbb7f间

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

WriteRaw

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

writer.WriteRaw("this & that");

WriteEntityRef

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

writer.WriteEntityRef("h");

WriteProcessingInstruction

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

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

WriteComment

写入注释,自动加入注释标志“29c34bdaf61639ad2e7e72dc03a6dddf”转化为“&”、“<”和“>”。

        2.ASCII码为0~(十六进制)的字符转化为“&#~“&#”。

        3.如果是在写属性的值则双引号“””转化为“"”;单引号 “’”转化为“'”。

        下面给大家写出一个例程,由于注释比较详细就不作过多解释了。

using System;
 2using System.IO;
 3using System.Xml;
 4
 5public class Sample
 6{
 7    private const string filename = "sampledata.xml";
 8
 9    public static void Main()
10    {
11        XmlTextWriter writer = null;
12
13        writer = new XmlTextWriter (filename, null);
14        //为使文件易读,使用缩进
15        writer.Formatting = Formatting.Indented;
16
17        //写XML声明
18        writer.WriteStartDocument();
19
20        //引用样式
21        String PItext="type=&#39;text/xsl&#39; href=&#39;book.xsl&#39;";
22        writer.WriteProcessingInstruction("xml-stylesheet", PItext);
23
24        //Write the DocumentType node
25        writer.WriteDocType("book", null , null, "<!ENTITY h &#39;hardcover&#39;>");
26        
27        //写入注释
28        writer.WriteComment("sample XML");
29    
30        //写一个元素(根元素)
31        writer.WriteStartElement("book");
32
33        // genre 属性
34        writer.WriteAttributeString("genre", "novel");
35    
36        // ISBN 属性
37        writer.WriteAttributeString("ISBN", "1-8630-014");
38
39        //书名元素
40        writer.WriteElementString("title", "The Handmaid&#39;s Tale");
41              
42        //Write the style element
43        writer.WriteStartElement("style");
44        writer.WriteEntityRef("h");
45        writer.WriteEndElement(); 
46
47        //价格元素
48        writer.WriteElementString("price", "19.95");
49
50        //写入 CDATA
51        writer.WriteCData("Prices 15% off!!");
52
53        //关闭根元素
54        writer.WriteEndElement();
55             
56        writer.WriteEndDocument();
57
58        //缓冲器内的内容写入文件
59        writer.Flush();
60        writer.Close();  
61
62        
63        XmlDocument doc = new XmlDocument();
64        
65        doc.PreserveWhitespace = true;
66        //加载文件
67        doc.Load(filename);  
68    
69        //XML文件的内容显示在控制台
70        Console.Write(doc.InnerXml);  
71        //等待用户阅读
72        Console.In.Read();
73    }
74}

The above is the detailed content of Detailed code examples for interpreting and writing XML files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn