在 C# 中读取和写入 XML

作者 : 慕源网 本文共10624个字,预计阅读时间需要27分钟 发布时间: 2022-03-12 共434人阅读

在本文中,您将了解如何使用 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 方法。 

textWriter.WriteStartDocument();   
textWriter.WriteEndDocument();   
textWriter.Close();   

WriteStartDocument 和 WriteEndDocument 方法打开和关闭要写入的文档。在开始写入之前,您必须先打开一个文档。WriteComment 方法将注释写入文档。它只需要一种字符串类型的参数。WriteString 方法将字符串写入文档。在 WriteString 的帮助下,WriteStartElement 和 WriteEndElement 方法对可用于将元素写入文档。WriteStartAttribute 和 WriteEndAttribute 对写入一个属性。

WriteNode 是更多的 write 方法,它将一个 XmlReader 作为文档的节点写入文档。例如,您可以使用 WriteProcessingInstruction 和 WriteDocType 方法来编写文档的 ProcessingInstruction 和 DocType 项。

//Write the ProcessingInstruction node   
string PI= "type='text/xsl' href='book.xsl'"   
textWriter.WriteProcessingInstruction("xml-stylesheet", PI);   
//'Write the DocumentType node   
textWriter.WriteDocType("book", Nothing, Nothing, "<!ENTITY h 'softcover'>");

下面的示例示例总结了所有这些方法,并创建了一个新的 xml 文档,其中包含一些项目,例如元素、属性、字符串、注释等。见清单 5-14。在此示例示例中,我们创建了一个新的 xml 文件 c:\xmlWriterText.xml。在这个示例示例中,我们使用 XmlTextWriter 创建一个新的 xml 文件 c:\xmlWriterTest.xml:

之后,我们使用 Writexxx 方法向文档添加注释和元素。之后,我们使用 XmlTextReader 读取 books.xml xml 文件,并使用 XmlTextWriter 将其元素添加到 xmlWriterTest.xml。

关于示例示例 3

在此示例示例中,我使用 XmlTextWriter 创建了一个新文件 myxmlFile.xml,并使用其各种写入方法来写入 XML 项。

示例示例 3。

using System;  
using System.Xml;  
namespace ReadingXML2 {  
    class Class1 {  
        static void Main(string[] args) {  
            // Create a new file in C:\\ dir  
            XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);  
            // Opens the document  
            textWriter.WriteStartDocument();  
            // Write comments  
            textWriter.WriteComment("First Comment XmlTextWriter Sample Example");  
            textWriter.WriteComment("myXmlFile.xml in root dir");  
            // Write first element  
            textWriter.WriteStartElement("Student");  
            textWriter.WriteStartElement("r", "RECORD", "urn:record");  
            // Write next element  
            textWriter.WriteStartElement("Name", "");  
            textWriter.WriteString("Student");  
            textWriter.WriteEndElement();  
            // Write one more element  
            textWriter.WriteStartElement("Address", "");  
            textWriter.WriteString("Colony");  
            textWriter.WriteEndElement();  
            // WriteChars  
            char[] ch = new char[3];  
            ch[0] = 'a';  
            ch[1] = 'r';  
            ch[2] = 'c';  
            textWriter.WriteStartElement("Char");  
            textWriter.WriteChars(ch, 0, ch.Length);  
            textWriter.WriteEndElement();  
            // Ends the document.  
            textWriter.WriteEndDocument();  
            // close writer  
            textWriter.Close();  
        }  
    }  
}   

使用 XmlDocument

XmlDocument 类表示一个 XML 文档。此类提供了我们在本文前面讨论过的类似方法和属性。

Load 和 LoadXml 是这个类的两个有用的方法。Load 方法从字符串、流、TextReader 或 XmlReader 加载 XML 数据。LoadXml 方法从指定的字符串加载 XML 文档。这个类的另一个有用的方法是保存。使用 Save 方法可以将 XML 数据写入字符串、流、TextWriter 或 XmlWriter。

关于示例示例 4

这个很小的示例示例非常容易理解。我们调用 XmlDocument 的 LoadXml 方法来加载 XML 片段,并调用 Save 将片段保存为 XML 文件。

示例示例 4。

//Create the XmlDocument.  
XmlDocument doc = new XmlDocument();  
doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy   
ex</Name></Student>"));   
//Save the document to a file.  
doc.Save("C:\\std.xml");   

如果您将 Console.Out 作为参数传递,您还可以使用 Save 方法在控制台上显示内容
。例如:
doc.Save(Console.Out);

关于示例示例 5

下面是一个如何使用 XmlTextReader 加载 XML 文档的示例。在这个示例示例中,我们使用 XmlTextReader 读取 books.xml 文件并调用其 Read 方法。之后我们调用 XmlDocumetn 的 Load 方法将 XmlTextReader 内容加载到 XmlDocument 并调用 Save 方法保存文档。将 Console.Out 作为 Save 方法参数传递会在控制台上显示数据

示例示例 5。

XmlDocument doc = new XmlDocument();  
//Load the the document with the last book node.  
XmlTextReader reader = new XmlTextReader("c:\\books.xml");  
reader.Read();   
// load reader   
doc.Load(reader);  
// Display contents on the console  
doc.Save(Console.Out);   

将数据从数据库写入 XML 文档

使用 XML 和 ADO.NET 模式,读取数据库并写入 XML 文档(反之亦然)并不是什么大问题。在本文的这一部分中,您将看到如何读取数据库表的数据并将内容写入 XML 文档。 

DataSet 类提供读取关系数据库表并将此表写入 XML 文件的方法。您使用 WriteXml 方法将数据集数据写入 XML 文件。

在这个示例示例中,我使用了Office 2000 及更高版本自带的常用Northwind 数据库。你可以使用任何你想要的数据库。您唯一需要做的就是对连接字符串和 SELECT SQL 查询进行章节化。

关于示例示例 6

在此示例中,我创建了一个数据适配器对象并选择了客户表的所有记录。之后,我可以使用填充方法从数据适配器填充数据集。

在此示例示例中,我使用了 OldDb 数据提供。您需要添加对 Syste.Data.OldDb 命名空间的引用才能在程序中使用 OldDb 数据适配器。从示例 6 中可以看出,首先我使用 OldDbConnection 创建了与北风数据库的连接。之后,我通过传递一个 SELECT SQL 查询和连接来创建一个数据适配器对象。一旦有了数据适配器,就可以使用数据适配器的 Fill 方法填充数据集对象。然后您可以使用 DataSet 的 WriteXml 方法,该方法创建一个 XML 文档并将其内容写入 XML 文档。在我们的示例中,我们读取Customers 表记录并将DataSet 内容写入C:\ 目录中的OutputXml.Xml 文件。

示例示例 6。

using System;  
using System.Xml;  
using System.Data;  
using System.Data.OleDb;  
namespace ReadingXML2 {  
    class Class1 {  
        static void Main(string[] args) {  
            // create a connection  
            OleDbConnection con = new OleDbConnection();  
            con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";  
            // create a data adapter  
            OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);  
            // create a new dataset  
            DataSet ds = new DataSet();  
            // fill dataset  
            da.Fill(ds, "Customers");  
            // write dataset contents to an xml file by calling WriteXml method  
            ds.WriteXml("C:\\OutputXML.xml");  
        }  
    }  
}  

总结

.NET Framework 库为使用 XML 文档提供了良好的支持。XmlReader、XmlWriter 及其派生类包含读取和写入 XML 文档的方法和属性。借助 XmlDocument 和 XmlDataDocument 类,您可以阅读整个文档。XmlDocument 的 Load 和 Save 方法分别加载阅读器或文件并保存文档。ADO.NET 提供了使用数据提供程序和 DataSet 对象读取数据库并将其内容写入 XML 文档的功能。


慕源网 » 在 C# 中读取和写入 XML

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录