VB.Net - XML 处理

  • 简述

    可扩展标记语言 (XML) 是一种标记语言,很像 HTML 或 SGML。这是万维网联盟推荐的,并作为开放标准提供。
    System.Xml.Net Framework 中的命名空间包含用于处理 XML 文档的类。以下是 System.Xml 命名空间中的一些常用类。
    序号 类别和描述
    1
    XmlAttribute
    代表一个属性。属性的有效值和默认值在文档类型定义 (DTD) 或模式中定义。
    2
    XmlCDataSection
    代表一个 CDATA 部分。
    3
    XmlCharacterData
    提供由多个类使用的文本操作方法。
    4
    XmlComment
    表示 XML 注释的内容。
    5
    XmlConvert
    对 XML 名称进行编码和解码,并提供在公共语言运行时类型和 XML 架构定义语言 (XSD) 类型之间进行转换的方法。转换数据类型时,返回的值与区域设置无关。
    6
    XmlDeclaration
    表示 XML 声明节点 <?xml version='1.0'...?>。
    7
    XmlDictionary
    实现用于优化 Windows Communication Foundation (WCF) 的 XML 读取器/写入器实现的字典。
    8
    XmlDictionaryReader
    Windows Communication Foundation (WCF) 从 XmlReader 派生的抽象类,用于执行序列化和反序列化。
    9
    XmlDictionaryWriter
    表示 Windows Communication Foundation (WCF) 从 XmlWriter 派生的抽象类,用于执行序列化和反序列化。
    10
    XmlDocument
    代表一个 XML 文档。
    11
    XmlDocumentFragment
    表示对树插入操作有用的轻量级对象。
    12
    XmlDocumentType
    表示文档类型声明。
    13
    XmlElement
    代表一个元素。
    14
    XmlEntity
    表示实体声明,例如 <!ENTITY...>。
    15
    XmlEntityReference
    代表一个实体引用节点。
    16
    XmlException
    返回有关最后一个异常的详细信息。
    17
    XmlImplementation
    定义一组 XmlDocument 对象的上下文。
    18
    XmlLinkedNode
    获取紧接在此节点之前或之后的节点。
    19
    XmlNode
    表示 XML 文档中的单个节点。
    20
    XmlNodeList
    表示节点的有序集合。
    21
    XmlNodeReader
    表示一个读取器,它提供对 XmlNode 中 XML 数据的快速、非缓存前向访问。
    22
    XmlNotation
    表示符号声明,例如 <!NOTATION... >。
    23
    XmlParserContext
    提供 XmlReader 解析 XML 片段所需的所有上下文信息。
    24
    XmlProcessingInstruction
    表示处理指令,XML 定义该指令将特定于处理器的信息保留在文档文本中。
    25
    XmlQualifiedName
    表示 XML 限定名称。
    26
    XmlReader
    表示提供对 XML 数据的快速、非缓存、只进访问的读取器。
    27
    XmlReaderSettings
    指定一组要在 Create 方法创建的 XmlReader 对象上支持的功能。
    28
    XmlResolver
    解析由统一资源标识符 (URI) 命名的外部 XML 资源。
    29
    XmlSecureResolver
    通过包装 XmlResolver 对象并限制基础 XmlResolver 可以访问的资源,帮助保护 XmlResolver 的另一个实现。
    30
    XmlSignificantWhitespace
    表示混合内容节点中标记之间的空白或 xml:space= 'preserve' 范围内的空白。这也称为显着空白。
    31
    XmlText
    表示元素或属性的文本内容。
    32
    XmlTextReader
    表示提供对 XML 数据的快速、非缓存、只进访问的读取器。
    33
    XmlTextWriter
    表示一个编写器,它提供一种快速、非缓存、只进的方式来生成包含符合 W3C 可扩展标记语言 (XML) 1.0 和 XML 中命名空间建议的 XML 数据的流或文件。
    34
    XmlUrlResolver
    解析由统一资源标识符 (URI) 命名的外部 XML 资源。
    35
    XmlWhitespace
    表示元素内容中的空白。
    36
    XmlWriter
    表示提供快速、非缓存、只进的方法来生成包含 XML 数据的流或文件的编写器。
    37
    XmlWriterSettings
    在由 XmlWriter.Create 方法创建的 XmlWriter 对象上指定要支持的一组功能。
  • XML 解析器 API

    XML 数据的两个最基本和最广泛使用的 API 是 SAX 和 DOM 接口。
    • Simple API for XML (SAX)- 在这里,您为感兴趣的事件注册回调,然后让解析器继续处理文档。当您的文档很大或您有内存限制时,这很有用,它会在从磁盘读取文件时解析文件,并且从不将整个文件存储在内存中。
    • Document Object Model (DOM) API - 这是万维网联盟的建议,其中将整个文件读入内存并以分层(基于树的)形式存储,以表示 XML 文档的所有特征。
    在处理大文件时,SAX 显然不能像 DOM 那样快地处理信息。另一方面,独占使用 DOM 确实会扼杀您的资源,尤其是在大量小文件上使用时。
    SAX 是只读的,而 DOM 允许更改 XML 文件。由于这两个不同的 API 从字面上相互补充,因此您没有理由不能在大型项目中同时使用它们。
    对于我们所有的 XML 代码示例,让我们使用一个简单的 XML 文件movies.xml 作为输入 -
    
    <?xml version = "1.0"?>
    <collection shelf = "New Arrivals">
       <movie title = "Enemy Behind">
          <type>War, Thriller</type>
          <format>DVD</format>
          <year>2003</year>
          <rating>PG</rating>
          <stars>10</stars>
          <description>Talk about a US-Japan war</description>
       </movie>
       <movie title = "Transformers">
          <type>Anime, Science Fiction</type>
          <format>DVD</format>
          <year>1989</year>
          <rating>R</rating>
          <stars>8</stars>
          <description>A schientific fiction</description>
       </movie>
       <movie title = "Trigun">
          <type>Anime, Action</type>
          <format>DVD</format>
          <episodes>4</episodes>
          <rating>PG</rating>
          <stars>10</stars>
          <description>Vash the Stampede!</description>
       </movie>
       <movie title = "Ishtar">
          <type>Comedy</type>
          <format>VHS</format>
          <rating>PG</rating>
          <stars>2</stars>
          <description>Viewable boredom</description>
       </movie>
    </collection>
    
  • 使用 SAX API 解析 XML

    在 SAX 模型中,您使用 XmlReaderXmlWriter 类来处理 XML 数据。
    XmlReader类用于以快速、只进和非缓存的方式读取 XML 数据。它读取 XML 文档或流。
  • 示例 1

    此示例演示从文件movies.xml 读取XML 数据。
    采取以下步骤 -
    • 在应用程序的 bin\Debug 文件夹中添加 movies.xml 文件。
    • 在 Form1.vb 文件中导入 System.Xml 命名空间。
    • 在表单中添加一个标签并将其文本更改为“Movies Galore”。
    • 添加三个列表框和三个按钮以显示来自 xml 文件的电影的标题、类型和描述。
    • 使用代码编辑器窗口添加以下代码。
    
    Imports System.Xml
    Public Class Form1
       Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
          ' Set the caption bar text of the form.   
          Me.Text = "jc2182.com"
       End Sub
       
       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
          ListBox1().Items.Clear()
          Dim xr As XmlReader = XmlReader.Create("movies.xml")
          Do While xr.Read()
             If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "movie" Then
                ListBox1.Items.Add(xr.GetAttribute(0))
             End If
          Loop
       End Sub
       
       Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
          ListBox2().Items.Clear()
          Dim xr As XmlReader = XmlReader.Create("movies.xml")
          Do While xr.Read()
             If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "type" Then
                ListBox2.Items.Add(xr.ReadElementString)
             Else
                xr.Read()
             End If
          Loop
       End Sub
       
       Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
          ListBox3().Items.Clear()
          Dim xr As XmlReader = XmlReader.Create("movies.xml")
          Do While xr.Read()
             If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "description" Then
                ListBox3.Items.Add(xr.ReadElementString)
             Else
                xr.Read()
             End If
          Loop
       End Sub
    End Class
    
    执行并运行上面的代码使用 StartMicrosoft Visual Studio 工具栏中可用的按钮。单击按钮将显示文件中电影的标题、类型和描述。
    VB.Net XML 处理示例 1
    XmlWriter类用于将 XML 数据写入流、文件或 TextWriter 对象。它也以只进、非缓存的方式工作。
  • 示例 2

    让我们通过在运行时添加一些数据来创建一个 XML 文件。采取以下步骤 -
    • 在窗体中添加一个 WebBrowser 控件和一个按钮控件。
    • 将按钮的 Text 属性更改为 Show Authors File。
    • 在代码编辑器中添加以下代码。
    
    Imports System.Xml
    Public Class Form1
       Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
          ' Set the caption bar text of the form.   
          Me.Text = "jc2182.com"
       End Sub
       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
          Dim xws As XmlWriterSettings = New XmlWriterSettings()
          xws.Indent = True
          xws.NewLineOnAttributes = True
          Dim xw As XmlWriter = XmlWriter.Create("authors.xml", xws)
          xw.WriteStartDocument()
          xw.WriteStartElement("Authors")
          xw.WriteStartElement("author")
          xw.WriteAttributeString("code", "1")
          xw.WriteElementString("fname", "Alex")
          xw.WriteElementString("lname", "Moo")
          xw.WriteEndElement()
          xw.WriteStartElement("author")
          xw.WriteAttributeString("code", "2")
          xw.WriteElementString("fname", "Priya")
          xw.WriteElementString("lname", "Sharma")
          xw.WriteEndElement()
          xw.WriteStartElement("author")
          xw.WriteAttributeString("code", "3")
          xw.WriteElementString("fname", "Anshuman")
          xw.WriteElementString("lname", "Mohan")
          xw.WriteEndElement()
          xw.WriteStartElement("author")
          xw.WriteAttributeString("code", "4")
          xw.WriteElementString("fname", "Bibhuti")
          xw.WriteElementString("lname", "Banerjee")
          xw.WriteEndElement()
          xw.WriteStartElement("author")
          xw.WriteAttributeString("code", "5")
          xw.WriteElementString("fname", "Riyan")
          xw.WriteElementString("lname", "Sengupta")
          xw.WriteEndElement()
          xw.WriteEndElement()
          xw.WriteEndDocument()
          xw.Flush()
          xw.Close()
          WebBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory + "authors.xml")
       End Sub
    End Class
    
    • 执行并运行上面的代码使用 StartMicrosoft Visual Studio 工具栏中可用的按钮。单击“显示作者文件”将在 Web 浏览器上显示新创建的 author.xml 文件。
    VB.Net XML 处理示例 2
  • 使用 DOM API 解析 XML

    根据文档对象模型(DOM),XML 文档由节点和节点的属性组成。这XmlDocument类用于实现 .Net Framework 的 XML DOM 解析器。它还允许您通过插入、删除或更新文档中的数据来修改现有的 XML 文档。
    以下是一些常用的方法 XmlDocument 类 -
    序号 方法名称和描述
    1
    AppendChild
    将指定节点添加到此节点的子节点列表的末尾。
    2
    CreateAttribute(String)
    创建具有指定名称的 XmlAttribute。
    3
    CreateComment
    创建包含指定数据的 XmlComment。
    4
    CreateDefaultAttribute
    创建具有指定前缀、本地名称和命名空间 URI 的默认属性。
    5
    CreateElement(String)
    创建具有指定名称的元素。
    6
    CreateNode(String, String, String)
    创建具有指定节点类型、Name 和 NamespaceURI 的 XmlNode。
    7
    CreateNode(XmlNodeType, String, String)
    创建具有指定 XmlNodeType、Name 和 NamespaceURI 的 XmlNode。
    8
    CreateNode(XmlNodeType, String, String, String)
    使用指定的 XmlNodeType、Prefix、Name 和 NamespaceURI 创建 XmlNode。
    9
    CreateProcessingInstruction
    创建具有指定名称和数据的 XmlProcessingInstruction。
    10
    CreateSignificantWhitespace
    创建一个 XmlSignificantWhitespace 节点。
    11
    CreateTextNode
    创建具有指定文本的 XmlText。
    12
    CreateWhitespace
    创建一个 XmlWhitespace 节点。
    13
    CreateXmlDeclaration
    创建具有指定值的 XmlDeclaration 节点。
    14
    GetElementById
    获取具有指定 ID 的 XmlElement。
    15
    GetElementsByTagName(String)
    返回一个 XmlNodeList,其中包含与指定 Name 匹配的所有后代元素的列表。
    16
    GetElementsByTagName(String, String)
    返回一个 XmlNodeList,其中包含与指定的 LocalName 和 NamespaceURI 匹配的所有后代元素的列表。
    17
    InsertAfter
    在指定的参考节点之后立即插入指定的节点。
    18
    InsertBefore
    在指定的参考节点之前立即插入指定的节点。
    19
    Load(Stream)
    从指定的流加载 XML 文档。
    20
    Load(String)
    从指定的 URL 加载 XML 文档。
    21
    Load(TextReader)
    从指定的 TextReader 加载 XML 文档。
    22
    Load(XmlReader)
    从指定的 XmlReader 加载 XML 文档。
    23
    LoadXml
    从指定的字符串加载 XML 文档。
    24
    PrependChild
    将指定节点添加到此节点的子节点列表的开头。
    25
    ReadNode
    根据 XmlReader 中的信息创建 XmlNode 对象。阅读器必须位于节点或属性上。
    26
    RemoveAll
    删除当前节点的所有子节点和/或属性。
    27
    RemoveChild
    删除指定的子节点。
    28
    ReplaceChild
    将子节点 oldChild 替换为 newChild 节点。
    29
    Save(Stream)
    将 XML 文档保存到指定的流。
    30
    Save(String)
    将 XML 文档保存到指定的文件。
    31
    Save(TextWriter)
    将 XML 文档保存到指定的 TextWriter。
    32
    Save(XmlWriter)
    将 XML 文档保存到指定的 XmlWriter。
  • 示例 3

    在本例中,让我们在 xml 文档authors.xml 中插入一些新节点,然后在列表框中显示所有作者的名字。
    采取以下步骤 -
    • 在您的应用程序的 bin/Debug 文件夹中添加authors.xml 文件(如果您尝试过最后一个示例,它应该在那里)
    • 导入 System.Xml 命名空间
    • 在窗体中添加一个列表框和一个按钮控件,并将按钮控件的文本属性设置为“显示作者”。
    • 使用代码编辑器添加以下代码。
    
    Imports System.Xml
    Public Class Form1
       Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
          ' Set the caption bar text of the form.   
          Me.Text = "jc2182.com"
       End Sub
       
       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
          ListBox1.Items.Clear()
          
          Dim xd As XmlDocument = New XmlDocument()
          xd.Load("authors.xml")
          
          Dim newAuthor As XmlElement = xd.CreateElement("author")
          newAuthor.SetAttribute("code", "6")
          
          Dim fn As XmlElement = xd.CreateElement("fname")
          fn.InnerText = "Bikram"
          newAuthor.AppendChild(fn)
          
          Dim ln As XmlElement = xd.CreateElement("lname")
          ln.InnerText = "Seth"
          newAuthor.AppendChild(ln)
          xd.DocumentElement.AppendChild(newAuthor)
          
          Dim tr As XmlTextWriter = New XmlTextWriter("movies.xml", Nothing)
          tr.Formatting = Formatting.Indented
          xd.WriteContentTo(tr)
          tr.Close()
          
          Dim nl As XmlNodeList = xd.GetElementsByTagName("fname")
          
          For Each node As XmlNode In nl
             ListBox1.Items.Add(node.InnerText)
          Next node
       End Sub
    End Class
    
    • 执行并运行上面的代码使用 StartMicrosoft Visual Studio 工具栏中可用的按钮。单击“显示作者”按钮将显示所有作者的名字,包括我们在运行时添加的作者。
    VB.Net XML 处理示例 3