在 C# 中读取和写入 XML
在本文中,您将了解如何使用 C# 语言在 Microsoft .NET 中读写 XML 文档。
首先,我将讨论 XML .NET Framework Library 命名空间和类。然后,您将看到如何读写 XML 文档。在本文的最后,我将向您展示如何利用 ADO.NET 和 XML .NET 模型从关系数据库读取和写入 XML 文档,反之亦然。
Microsoft .NET XML 命名空间和类介绍
在开始使用 .NET Framework 中的 XML 文档之前,了解 .NET 命名空间和 .NET 运行时库提供的类非常重要。.NET 提供了五个命名空间——System.Xml、System.Xml.Schema、System.Xml.Serialization、System.Xml.XPath 和 System.Xml.Xsl 来支持 XML 类。
System.Xml 命名空间包含主要的 XML 类。此名称空间包含许多用于读取和写入 XML 文档的类。在本文中,我们将专注于读写类。这些读取器和写入器类用于读取和写入 XML 文档。这些类是 – XmlReader、XmlTextReader、XmlValidatingReader、XmlNodeReader、XmlWriter 和 XmlTextWriter。如您所见,有四个读取器和两个写入器类。
XmlReader 类是一个抽象基类,包含读取文档的方法和属性。Read 方法读取流中的一个节点。除了阅读功能外,该类还包含在文档节点中导航的方法。其中一些方法是 MoveToAttribute、MoveToFirstAttribute、MoveToContent、MoveToFirstContent、MoveToElement 和 MoveToNextAttribute。ReadString、ReadInnerXml、ReadOuterXml 和 ReadStartElement 是更多的读取方法。这个类还有一个方法 Skip 来跳过当前节点并移动到下一个节点。我们将在示例示例中看到这些方法。
XmlTextReader、XmlNodeReader 和 XmlValidatingReader 类派生自 XmlReader 类。正如他们的名字所解释的,它们用于阅读文本、节点和模式。
XmlWrite 类包含将数据写入 XML 文档的功能。该类提供了许多写方法来编写 XML 文档项。此类是 XmlTextWriter 类的基类,我们将在示例示例中使用它。
XmlNode _类起着重要的作用。虽然,此类表示 XML 的单个节点,但它可能是 XML 文档的根节点并且可以表示整个文件。此类是用于插入、删除和替换节点以及在文档中导航的许多有用类的抽象基类。它还包含用于获取父级或子级、名称、最后一个子级、节点类型等的属性。从 XmlNode 派生的三个主要类是 XmlDocument、XmlDataDocument 和 XmlDocumentFragment。XmlDocument 类表示一个 XML 文档,并提供加载和保存文档的方法和属性。它还提供添加 XML 项目(例如属性、注释、空间、元素和新节点)的功能。Load 和 LoadXml 方法可用于加载 XML 文档,而 Save 方法可用于保存文档。XmlDocumentFragment 类表示一个文档片段,可用于添加到文档中。XmlDataDocument 类提供处理 ADO.NET 数据集对象的方法和属性。
尽管上面讨论了类,System.Xml 命名空间包含更多类。其中很少有 XmlConvert、XmlLinkedNode 和 XmlNodeList。
Xml 系列中的下一个命名空间是 System.Xml.Schema。它使用 XML 架构进行分类,例如 XmlSchema、XmlSchemaAll、XmlSchemaXPath、XmlSchemaType。
System.Xml.Serialization 命名空间包含用于将对象序列化为 XML 格式文档或流的类。
System.Xml.XPath Namespce 包含 XPath 相关类以使用 XPath 规范。此命名空间具有以下类 -XPathDocument、XPathExression、XPathNavigator 和 XPathNodeIterator。在 XpathDocument 的帮助下,XpathNavigator 提供了通过 XML 文档的快速导航。此类包含许多用于在文档中移动的 Move 方法。
System.Xml.Xsl 命名空间包含使用 XSL/T 转换的类。
读取 XML 文档
在我的示例应用程序中,我使用 books.xml 通过 XmlTextReader 读取和显示其数据。该文件带有 VS.NET 示例。您可以在您的机器上搜索它并在以下行中更改文件的路径:
XmlTextReader textReader = new XmlTextReader(“C:\\books.xml”);
或者,您可以使用任何 XML 文件。
XmlTextReader、XmlNodeReader 和 XmlValidatingReader 类派生自 XmlReader 类。除了 XmlReader 方法和属性之外,这些类还包含分别用于读取文本、节点和模式的成员。我正在使用 XmlTextReader 类来读取 XML 文件。您通过在构造函数中将文件名作为参数传递来读取文件。
XmlTextReader textReader = new XmlTextReader(“C:\\books.xml”);
创建 XmlTextReader 实例后,调用 Read 方法开始读取文档。调用 read 方法后,您可以读取文档中存储的所有信息和数据。XmlReader 类具有 Name、BaseURI、Depth、LineNumber 等属性。
清单 1 使用这些属性读取一个文档并显示一个节点信息。
关于示例示例 1
在此示例示例中,我使用 XmlTextReader 读取了一个 XML 文件,并调用 Read 方法逐个读取其节点,直到文件结束并将内容显示到控制台输出。
示例示例 1。
using System;
using System.Xml;
namespace ReadXml1 {
class Class1 {
static void Main(string[] args) {
// Create an isntance of XmlTextReader and call Read method to read the file
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
textReader.Read();
// If the node has value
while (textReader.Read()) {
// Move to fist element
textReader.MoveToElement();
Console.WriteLine("XmlTextReader Properties Test");
Console.WriteLine("===================");
// Read this element's properties and display them on console
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());
}
}
}
}
当您想知道文档的内容类型时,XmlTextReader 的 NodeType 属性很重要。XmlNodeType 枚举对每种类型的 XML 项都有一个成员,例如 Attribute、CDATA、Element、Comment、Document、DocumentType、Entity、ProcessInstruction、WhiteSpace 等。
清单 2 代码示例读取一个 XML 文档,找到一个节点类型并在最后写入一个文档有多少个节点类型的信息。
强烈推荐
海量程序代码,编程资源,无论你是小白还是大神研究借鉴别人优秀的源码产品学习成熟的专业技术强势助力帮你提高技能与技能。在此处获取,给你一个全面升级的机会。只有你更值钱,才能更赚钱
关于示例示例 2
在这个示例示例中,我使用 XmlTextReader 读取了一个 XML 文件,并调用 Read 方法逐个读取其节点,直到文件末尾。读取一个节点后,我检查它的 NodeType 属性以找到该节点并将节点内容写入控制台并跟踪特定类型节点的数量。最后,我在文档中显示了不同类型节点的总数。
示例示例 2。
using System;
using System.Xml;
namespace ReadingXML2 {
class Class1 {
static void Main(string[] args) {
int ws = 0;
int pi = 0;
int dc = 0;
int cc = 0;
int ac = 0;
int et = 0;
int el = 0;
int xd = 0;
// Read a document
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
// Read until end of file
while (textReader.Read()) {
XmlNodeType nType = textReader.NodeType;
// If node type us a declaration
if (nType == XmlNodeType.XmlDeclaration) {
Console.WriteLine("Declaration:" + textReader.Name.ToString());
xd = xd + 1;
}
// if node type is a comment
if (nType == XmlNodeType.Comment) {
Console.WriteLine("Comment:" + textReader.Name.ToString());
cc = cc + 1;
}
// if node type us an attribute
if (nType == XmlNodeType.Attribute) {
Console.WriteLine("Attribute:" + textReader.Name.ToString());
ac = ac + 1;
}
// if node type is an element
if (nType == XmlNodeType.Element) {
Console.WriteLine("Element:" + textReader.Name.ToString());
el = el + 1;
}
// if node type is an entity\
if (nType == XmlNodeType.Entity) {
Console.WriteLine("Entity:" + textReader.Name.ToString());
et = et + 1;
}
// if node type is a Process Instruction
if (nType == XmlNodeType.Entity) {
Console.WriteLine("Entity:" + textReader.Name.ToString());
pi = pi + 1;
}
// if node type a document
if (nType == XmlNodeType.DocumentType) {
Console.WriteLine("Document:" + textReader.Name.ToString());
dc = dc + 1;
}
// if node type is white space
if (nType == XmlNodeType.Whitespace) {
Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());
ws = ws + 1;
}
}
// Write the summary
Console.WriteLine("Total Comments:" + cc.ToString());
Console.WriteLine("Total Attributes:" + ac.ToString());
Console.WriteLine("Total Elements:" + el.ToString());
Console.WriteLine("Total Entity:" + et.ToString());
Console.WriteLine("Total Process Instructions:" + pi.ToString());
Console.WriteLine("Total Declaration:" + xd.ToString());
Console.WriteLine("Total DocumentType:" + dc.ToString());
Console.WriteLine("Total WhiteSpaces:" + ws.ToString());
}
} }
编写 XML 文档
XmlWriter 类包含写入 XML 文档的功能。它是通过 XmlTextWriter 和 XmlNodeWriter 类使用的抽象基类。它包含写入 XML 文档的方法和属性。这个类有几个Writexxx 方法来编写XML 文档的每种类型的项目。例如,WriteNode、WriteString、WriteAttributes、WriteStartElement 和 WriteEndElement 就是其中的一部分。其中一些方法用于开始和结束对。例如,要编写一个元素,您需要调用 WriteStartElement,然后编写一个字符串,后跟 WriteEndElement。
除了许多方法外,该类还具有三个属性。WriteState、XmlLang 和 XmlSpace。WriteState 获取并设置XmlWriter 类的状态。
虽然不可能在这里描述所有的 Writexxx 方法,但让我们看看其中的一些。
我们需要做的第一件事是使用其构造函数创建一个 XmlTextWriter 实例。XmlTextWriter 具有三个重载的构造函数,它们可以将字符串、流或 TextWriter 作为参数。我们将传递一个字符串(文件名)作为参数,我们将在 C:\ root 中创建它。
在我的示例示例中,我在 C:\\ 根目录中创建了一个文件 myXmlFile.xml。
// 在 C:\\ 目录中创建一个新文件
XmlTextWriter textWriter = new XmlTextWriter( "C:\\myXmFile.xml" , null ) ;
创建实例后,首先调用我们的 WriterStartDocument。完成编写后,调用 WriteEndDocument 和 TextWriter 的 Close 方法。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!