


Detailed explanation of .net reading and writing xml documents
这篇文章主要介绍了.net读写xml文档的示例,需要的朋友可以参考下
一 .Net框架中与XML有关的命名空间
System.Xml
包含了一些和XML文档的读写操作相关的类,它们分别是:XmlReader、XmlTextReader、XmlValidatingReader、XmlNodeReader、XmlWriter、XmlTextWriter 以及 XmlNode(它的子类包括:XmlDocument、XmlDataDocument、XmlDocumentFragment)等类。
System.Xml.Schema
包含了和XML模式相关的类,这些类包括XmlSchema、XmlSchemaAll、XmlSchemaXPath以及XmlSchemaType等类。
System.Xml.Serialization
包含了和XML文档的序列化和反序列化操作相关的类。
序列化:将XML格式的数据转化为流格式的数据,并能在网络中传输;
反序列化:完成相反的操作,即将流格式的数据还原成XML格式的数据。
System.Xml.Xpath
包含了XPathDocument、XPathExression、XPathNavigator以及XPathNodeIterator等类,这些类能完成XML文档的导航功能。
(在XPathDocument类的协助下,XPathNavigator类能完成快速的XML文档导航功能,该类为程序员提供了许多Move方法以完成导航功能。)
System.Xml.Xsl
完成XSLT的转换功能。
二 写XML文档的方法
用XmlWriter类实现写操作,该类包含了写XML文档所需的方法和属性,它是XmlTextWriter类和XmlNodeWriter类的基类。
写操作的有些方法是成对出现的,比如你要写入一个元素,首先调用WriteStartElement方法—>写入实际内容—>调用WriteEndElement方法结束。
下面通过其子类 XmlTextWriter 来说明如何写XML文档。
XmlTextWriter textWriter = New XmlTextWriter("C:\\myXmFile.xml", null);
在创建完对象后,我们调用WriterStartDocument方法开始写XML文档;
在完成写工作后,就调用WriteEndDocument结束写过程,并调用Close方法将它关闭。
在写的过程中,我们可以:
调用WriteComment方法来添加说明;
通过调用WriteString方法来添加一个字符串;
通过调用WriteStartElement和WriteEndElement方法对来添加一个元素;
通过调用WriteStartAttribute和WriteEndAttribute方法对来添加一个属性;
通过调用WriteNode方法来添加整的一个节点;
其它的写的方法还包括WriteProcessingInstruction和WriteDocType等等。
下面的示例介绍如何具体运用这些方法来完成XML文档的写工作。
代码如下:
using System; using System.Xml; namespace WriteXML { class Class1 { static void Main( string[] args ) { try { // 创建XmlTextWriter类的实例对象 XmlTextWriter textWriter = new XmlTextWriter("C:\\w3sky.xml", null); textWriter.Formatting = Formatting.Indented; // 开始写过程,调用WriteStartDocument方法 textWriter.WriteStartDocument(); // 写入说明 textWriter.WriteComment("First Comment XmlTextWriter Sample Example"); textWriter.WriteComment("w3sky.xml in root dir"); //创建一个节点 textWriter.WriteStartElement("Administrator"); textWriter.WriteElementString("Name", "formble"); textWriter.WriteElementString("site", "w3sky.com"); textWriter.WriteEndElement(); // 写文档结束,调用WriteEndDocument方法 textWriter.WriteEndDocument(); // 关闭textWriter textWriter.Close(); } catch(System.Exception e) { Console.WriteLine(e.ToString()); } } } }
三 读XML文档的方法
用XmlTextReader类的对象来读取该XML文档。在创建新对象的构造函数中指明XML文件的位置即可。
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
XmlTextReader 类中的属性 NodeType 可以知道其节点的节点类型。通过与枚举类型 XmlNodeType 中的元素的比较,可以获取相应节点的节点类型并对其完成相关的操作。
枚举类型 XmlNodeType 中包含了诸如XmlDeclaration、Attribute、CDATA、Element、Comment、Document、DocumentType、Entity、ProcessInstruction以及WhiteSpace等XML项的类型。
下面的示例是以读取"books.xml"文件创建对象,通过该xml对象的Name、BaseURI、Depth、LineNumber等属性来获取相关信息,并显示在控制台中。(运用VS.net开发工具附带的"books.xml"文件来作为示例)
代码如下:
using System; using System.Xml; namespace ReadXml { class Class1 { static void Main( string[] args ) { // 创建一个XmlTextReader类的对象并调用Read方法来读取XML文件 XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); textReader.Read(); // 节点非空则执行循环体 while ( textReader.Read() ) { // 读取第一个元素 textReader.MoveToElement(); Console.WriteLine("XmlTextReader Properties Test"); Console.WriteLine("==================="); // 读取该元素的属性并显示在控制台中 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()); } } } }
四 运用XmlDocument类
XmlDocument类代表了XML文档,它能完成与整个XML文档相关的各类操作,同时和其相关的XmlDataDocument类也是非常重要的,值得深入研究。 该类包含了Load、LoadXml以及Save等重要的方法。
Load方法: 可以从一个字符串指定的XML文件或是一个流对象、一个TextReader对象、一个XmlReader对象导入XML数据。
LoadXml方法: 则完成从一个特定的XML文件导入XML数据的功能。
Save方法: 则将XML数据保存到一个XML文件中或是一个流对象、一个TextWriter对象、一个XmlWriter对象中。
下面的示例中,用到了XmlDocument类对象的LoadXml方法,它从一个XML文档段中读取XML数据并调用其Save方法将数据保存在一个文件中。
代码如下:
// 创建一个XmlDocument类的对象 XmlDocument doc = new XmlDocument(); doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy Lex</Name></Student>")); // 保存到文件中 doc.Save("C:\\student.xml"); // 还可以通过改变Save方法中参数,将XML数据显示在控制台中,方法如下: doc.Save(Console.Out); 下面的示例中,用到了一个XmlTextReader对象,通过它读取"books.xml"文件中的XML数据。然后创建一个XmlDocument对象并载入XmlTextReader对象,这样XML数据就被读到XmlDocument对象中了。最后,通过该对象的Save方法将XML数据显示在控制台中。 XmlDocument doc = new XmlDocument(); // 创建一个XmlTextReader对象,读取XML数据 XmlTextReader reader = new XmlTextReader("c:\\books.xml"); reader.Read(); // 载入XmlTextReader类的对象 doc.Load(reader); // 将XML数据显示在控制台中 doc.Save(Console.Out);
xml文件
代码如下:
<?xml version='1.0'?> <!-- This file represents a fragment of a 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>
另外一个.net操作xml文件示例
代码如下:
//设置配置文件物理路径 public string xmlPath = "/manage/spider/config.xml"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //设置程序物理路径+文件物理路径 string path = Request.PhysicalApplicationPath + xmlPath; //获取XML元素对象 XElement config = XElement.Load(path); if (config != null) { //获得节点子元素 XElement eleAmazonDetailUrl = config.Element("AmazonDetailUrl"); XElement eleAmazonListUrl = config.Element("AmazonListUrl"); XElement eleHz = config.Element("Hz"); XElement eleCount = config.Element("Count"); //在页面上呈现取到的数据 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) { //设置XML文件路径 string path = Request.PhysicalApplicationPath + xmlPath; //设置节点的名称和内容 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()) ); //将元素序列化到指定路径的XML文件当中 root.Save(path); }
The above is the detailed content of Detailed explanation of .net reading and writing xml documents. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach
