分享

XmlDocument 类 (System.Xml)

 龙门过客栈 2017-11-17



发布日期: 2016年7月

表示 XML 文档。 可使用此类在文档中加载、验证、编辑、添加和放置 XML。

命名空间:   System.Xml
程序集:  System.Xml(位于 System.Xml.dll)

System.Object
  System.Xml.XmlNode
    System.Xml.XmlDocument
      System.Configuration.ConfigXmlDocument
      System.Xml.XmlDataDocument



Public Class XmlDocument
	Inherits XmlNode

名称说明
System_CAPS_pubmethodXmlDocument()

初始化 XmlDocument 类的新实例。

System_CAPS_protmethodXmlDocument(XmlImplementation)

使用指定的 XmlDocument 初始化 XmlImplementation 类的新实例。

System_CAPS_pubmethodXmlDocument(XmlNameTable)

使用指定的 XmlDocument 初始化 XmlNameTable 类的新实例。

名称说明
System_CAPS_pubpropertyAttributes

获取 XmlAttributeCollection 包含此节点的属性。(继承自 XmlNode。)

System_CAPS_pubpropertyBaseURI

获取当前节点的基 URI。(覆盖 XmlNode.BaseURI。)

System_CAPS_pubpropertyChildNodes

获取节点的所有子节点。(继承自 XmlNode。)

System_CAPS_pubpropertyDocumentElement

获取文档的根 XmlElement

System_CAPS_pubpropertyDocumentType

获取包含 DOCTYPE 声明的节点。

System_CAPS_pubpropertyFirstChild

获取节点的第一个子级。(继承自 XmlNode。)

System_CAPS_pubpropertyHasChildNodes

获取一个值,该值指示此节点是否有任何子节点。(继承自 XmlNode。)

System_CAPS_pubpropertyImplementation

获取当前文档的 XmlImplementation 对象。

System_CAPS_pubpropertyInnerText

在所有情况下引发 InvalidOperationException(覆盖 XmlNode.InnerText。)

System_CAPS_pubpropertyInnerXml

获取或设置表示当前节点的子级的标记。(覆盖 XmlNode.InnerXml。)

System_CAPS_pubpropertyIsReadOnly

获取一个值,该值指示当前节点是否是只读的。(覆盖 XmlNode.IsReadOnly。)

System_CAPS_pubpropertyItem(String)

获取具有指定的第一个子元素 Name(继承自 XmlNode。)

System_CAPS_pubpropertyItem(String, String)

获取具有指定的第一个子元素 LocalNameNamespaceURI(继承自 XmlNode。)

System_CAPS_pubpropertyLastChild

获取节点的最后一个子级。(继承自 XmlNode。)

System_CAPS_pubpropertyLocalName

获取节点的本地名称。(覆盖 XmlNode.LocalName。)

System_CAPS_pubpropertyName

获取节点的限定名称。(覆盖 XmlNode.Name。)

System_CAPS_pubpropertyNamespaceURI

获取该节点的命名空间 URI。(继承自 XmlNode。)

System_CAPS_pubpropertyNameTable

获取与此实现关联的 XmlNameTable

System_CAPS_pubpropertyNextSibling

获取紧接在该节点之后的节点。(继承自 XmlNode。)

System_CAPS_pubpropertyNodeType

获取当前节点的类型。(覆盖 XmlNode.NodeType。)

System_CAPS_pubpropertyOuterXml

获取包含此节点及其所有子节点的标记。(继承自 XmlNode。)

System_CAPS_pubpropertyOwnerDocument

获取当前节点所属的 XmlDocument(覆盖 XmlNode.OwnerDocument。)

System_CAPS_pubpropertyParentNode

获取该节点的父节点(针对可以拥有父级的节点)。(覆盖 XmlNode.ParentNode。)

System_CAPS_pubpropertyPrefix

获取或设置该节点的命名空间前缀。(继承自 XmlNode。)

System_CAPS_pubpropertyPreserveWhitespace

获取或设置一个值,该值指示是否在元素内容中保留空白区域。

System_CAPS_pubpropertyPreviousSibling

获取紧接在该节点之前的节点。(继承自 XmlNode。)

System_CAPS_pubpropertyPreviousText

获取紧接在该节点之前的文本节点。(继承自 XmlNode。)

System_CAPS_pubpropertySchemaInfo

返回节点的后架构验证信息集 (PSVI)。(覆盖 XmlNode.SchemaInfo。)

System_CAPS_pubpropertySchemas

获取或设置与此 XmlDocument 关联的 XmlSchemaSet 对象。

System_CAPS_pubpropertyValue

获取或设置节点的值。(继承自 XmlNode。)

System_CAPS_pubpropertyXmlResolver

设置 XmlResolver 以用于解析外部资源。

名称说明
System_CAPS_pubmethodAppendChild(XmlNode)

将指定的节点添加到该节点的子节点列表的末尾。(继承自 XmlNode。)

System_CAPS_pubmethodClone()

创建此节点的副本。(继承自 XmlNode。)

System_CAPS_pubmethodCloneNode(Boolean)

创建此节点的副本。(覆盖 XmlNode.CloneNode(Boolean)。)

System_CAPS_pubmethodCreateAttribute(String)

创建具有指定 NameXmlAttribute

System_CAPS_pubmethodCreateAttribute(String, String)

创建具有指定限定名和 NamespaceURIXmlAttribute

System_CAPS_pubmethodCreateAttribute(String, String, String)

创建一个具有指定的 PrefixLocalNameNamespaceURIXmlAttribute

System_CAPS_pubmethodCreateCDataSection(String)

创建包含指定数据的 XmlCDataSection

System_CAPS_pubmethodCreateComment(String)

创建包含指定数据的 XmlComment

System_CAPS_protmethodCreateDefaultAttribute(String, String, String)

创建具有指定前缀、本地名称和命名空间 URI 的默认属性。

System_CAPS_pubmethodCreateDocumentFragment()

创建一个 XmlDocumentFragment

System_CAPS_pubmethodCreateDocumentType(String, String, String, String)

返回新 XmlDocumentType 对象。

System_CAPS_pubmethodCreateElement(String)

创建具有指定名称的元素。

System_CAPS_pubmethodCreateElement(String, String)

创建具有限定名和 NamespaceURIXmlElement

System_CAPS_pubmethodCreateElement(String, String, String)

创建具有指定 PrefixLocalNameNamespaceURI 的元素。

System_CAPS_pubmethodCreateEntityReference(String)

创建具有指定名称的 XmlEntityReference

System_CAPS_pubmethodCreateNavigator()

创建一个用于导航此文档的新 XPathNavigator 对象。(覆盖 XmlNode.CreateNavigator()。)

System_CAPS_protmethodCreateNavigator(XmlNode)

创建 XPathNavigator 对象,以定位位于指定的 XmlNode 上的此文档。

System_CAPS_pubmethodCreateNode(String, String, String)

创建具有指定的节点类型、NameNamespaceURIXmlNode

System_CAPS_pubmethodCreateNode(XmlNodeType, String, String)

创建一个具有指定的 XmlNodeTypeNameNamespaceURIXmlNode

System_CAPS_pubmethodCreateNode(XmlNodeType, String, String, String)

创建一个具有指定的XmlNodeTypePrefixNameNamespaceURIXmlNode

System_CAPS_pubmethodCreateProcessingInstruction(String, String)

创建一个具有指定名称和数据的 XmlProcessingInstruction

System_CAPS_pubmethodCreateSignificantWhitespace(String)

创建一个 XmlSignificantWhitespace 节点。

System_CAPS_pubmethodCreateTextNode(String)

创建具有指定文本的 XmlText

System_CAPS_pubmethodCreateWhitespace(String)

创建一个 XmlWhitespace 节点。

System_CAPS_pubmethodCreateXmlDeclaration(String, String, String)

创建一个具有指定值的 XmlDeclaration 节点。

System_CAPS_pubmethodEquals(Object)

确定指定的对象是否等于当前对象。(继承自 Object。)

System_CAPS_protmethodFinalize()

在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object。)

System_CAPS_pubmethodGetElementById(String)

获取具有指定 ID 的 XmlElement

System_CAPS_pubmethodGetElementsByTagName(String)

返回一个 XmlNodeList,它包含与指定 Name 匹配的所有子代元素的列表。

System_CAPS_pubmethodGetElementsByTagName(String, String)

返回一个 XmlNodeList,它包含与指定 LocalNameNamespaceURI 匹配的所有子代元素的列表。

System_CAPS_pubmethodGetEnumerator()

获取循环访问当前节点中子节点的枚举。(继承自 XmlNode。)

System_CAPS_pubmethodGetHashCode()

作为默认哈希函数。(继承自 Object。)

System_CAPS_pubmethodGetNamespaceOfPrefix(String)

查找最接近 xmlns 为给定的前缀的当前节点范围内,在声明中返回的命名空间 URI 声明。(继承自 XmlNode。)

System_CAPS_pubmethodGetPrefixOfNamespace(String)

查找最接近 xmlns 位于给定命名空间 URI,它用于当前节点范围内,并返回声明中定义的前缀声明。(继承自 XmlNode。)

System_CAPS_pubmethodGetType()

获取当前实例的 Type(继承自 Object。)

System_CAPS_pubmethodImportNode(XmlNode, Boolean)

将节点从另一个文档导入到当前文档。

System_CAPS_pubmethodInsertAfter(XmlNode, XmlNode)

将指定的节点紧接着插入指定的引用节点之后。(继承自 XmlNode。)

System_CAPS_pubmethodInsertBefore(XmlNode, XmlNode)

将指定的节点紧接着插入指定的引用节点之前。(继承自 XmlNode。)

System_CAPS_pubmethodLoad(Stream)

从指定的流加载 XML 文档。

System_CAPS_pubmethodLoad(String)

从指定的 URL 加载 XML 文档。

System_CAPS_pubmethodLoad(TextReader)

从指定的 TextReader 加载 XML 文档。

System_CAPS_pubmethodLoad(XmlReader)

从指定的 XmlReader 加载 XML 文档。

System_CAPS_pubmethodLoadXml(String)

从指定的字符串加载 XML 文档。

System_CAPS_protmethodMemberwiseClone()

创建当前 Object 的浅表副本。(继承自 Object。)

System_CAPS_pubmethodNormalize()

将此 XmlNode 下子树完全深度中的所有 XmlText 节点都转换成“正常”形式,在这种形式中只有标记(即标记、注释、处理指令、CDATA 节和实体引用)分隔 XmlText 节点,也就是说,没有相邻的 XmlText 节点。(继承自 XmlNode。)

System_CAPS_pubmethodPrependChild(XmlNode)

将指定的节点添加到该节点的子节点列表的开头。(继承自 XmlNode。)

System_CAPS_pubmethodReadNode(XmlReader)

根据 XmlReader 中的信息创建一个 XmlNode 对象。 读取器必须定位在节点或属性上。

System_CAPS_pubmethodRemoveAll()

移除当前节点的所有子节点和/或属性。(继承自 XmlNode。)

System_CAPS_pubmethodRemoveChild(XmlNode)

移除指定的子节点。(继承自 XmlNode。)

System_CAPS_pubmethodReplaceChild(XmlNode, XmlNode)

替换子节点 oldChildnewChild 节点。(继承自 XmlNode。)

System_CAPS_pubmethodSave(Stream)

将 XML 文档保存到指定的流。

System_CAPS_pubmethodSave(String)

将 XML 文档保存到指定的文件。 如果存在指定文件,则此方法会覆盖它。

System_CAPS_pubmethodSave(TextWriter)

将 XML 文档保存到指定的 TextWriter

System_CAPS_pubmethodSave(XmlWriter)

将 XML 文档保存到指定的 XmlWriter

System_CAPS_pubmethodSelectNodes(String)

选择匹配 XPath 表达式的节点列表。(继承自 XmlNode。)

System_CAPS_pubmethodSelectNodes(String, XmlNamespaceManager)

选择匹配 XPath 表达式的节点列表。 使用所提供解析 XPath 表达式中找到的任何前缀 XmlNamespaceManager(继承自 XmlNode。)

System_CAPS_pubmethodSelectSingleNode(String)

选择第一个 XmlNode ,与 XPath 表达式匹配。(继承自 XmlNode。)

System_CAPS_pubmethodSelectSingleNode(String, XmlNamespaceManager)

选择第一个 XmlNode ,与 XPath 表达式匹配。 使用所提供解析 XPath 表达式中找到的任何前缀 XmlNamespaceManager(继承自 XmlNode。)

System_CAPS_pubmethodSupports(String, String)

测试 DOM 实现是否实现特定的功能。(继承自 XmlNode。)

System_CAPS_pubmethodToString()

返回表示当前对象的字符串。(继承自 Object。)

System_CAPS_pubmethodValidate(ValidationEventHandler)

验证 XmlDocument 是不是 Schemas 属性中包含的 XML 架构定义语言 (XSD) 架构。

System_CAPS_pubmethodValidate(ValidationEventHandler, XmlNode)

根据 Schemas 属性中的 XML 架构定义语言 (XSD) 架构,验证指定的 XmlNode 对象。

System_CAPS_pubmethodWriteContentTo(XmlWriter)

XmlDocument 节点的所有子级保存到指定的 XmlWriter 中。(覆盖 XmlNode.WriteContentTo(XmlWriter)。)

System_CAPS_pubmethodWriteTo(XmlWriter)

XmlDocument 节点保存到指定的 XmlWriter(覆盖 XmlNode.WriteTo(XmlWriter)。)

名称说明
System_CAPS_pubeventNodeChanged

当属于该文档的节点的 Value 已被更改时发生。

System_CAPS_pubeventNodeChanging

当属于该文档的节点的 Value 将被更改时发生。

System_CAPS_pubeventNodeInserted

将属于该文档的节点插入另一个节点时发生。

System_CAPS_pubeventNodeInserting

将属于该文档的节点插入另一个节点时发生。

System_CAPS_pubeventNodeRemoved

当属于该文档的节点已从其父级中移除时发生。

System_CAPS_pubeventNodeRemoving

当属于该文档的节点将从文档中移除时发生。

名称说明
System_CAPS_pubinterfaceSystem_CAPS_privmethodIEnumerable.GetEnumerator()

有关此成员的说明,请参阅 XmlNode.GetEnumerator(继承自 XmlNode。)

System_CAPS_pubinterfaceSystem_CAPS_privmethodICloneable.Clone()

有关此成员的说明,请参阅 XmlNode.Clone(继承自 XmlNode。)

名称说明
System_CAPS_pubmethodAsParallel()

已重载。启用查询的并行化。(由 ParallelEnumerable 定义。)

System_CAPS_pubmethodAsQueryable()

已重载。将转换 IEnumerableIQueryable(由 Queryable 定义。)

System_CAPS_pubmethodCast(Of TResult)()

将强制转换的元素 IEnumerable 为指定的类型。(由 Enumerable 定义。)

System_CAPS_pubmethodOfType(Of TResult)()

筛选的元素 IEnumerable 根据指定的类型。(由 Enumerable 定义。)

XmlDocument类是 XML 文档的内存中表示。 它实现 W3CXML 文档对象模型 (DOM)级别 1 核心和核心 DOM 级别 2。

DOM代表文档对象模型 若要了解更多有关它,请参阅XML 文档对象模型 (DOM)

你可以通过将 XML 加载到 DOMXmlDocument类,以及然后以编程方式读取、 修改和删除 XML 文档中。

如果你想要将其撬打开XmlDocument类,请参阅如何实现,请参阅Reference Source

启动与 XML 文档与此类似。 它是在集合中的几个丛书。 但它包含你将会发现任何 XML 文档; 中的基本内容命名空间、 表示数据的元素和特性用于描述数据。

<?xml version="1.0" encoding="utf-8"?>
<books xmlns="http://www./books">
  <book genre="novel" ISBN="1-861001-57-8" publicationdate="1823-01-28">
    <title>Pride And Prejudice</title>
    <price>24.95</price>
  </book>
  <book genre="novel" ISBN="1-861002-30-1" publicationdate="1985-01-01">
    <title>The Handmaid's Tale</title>
    <price>29.95</price>
  </book>
  <book genre="novel" ISBN="1-861001-45-3" publicationdate="1811-01-01">
    <title>Sense and Sensibility</title>
    <price>19.95</price>
  </book>
</books>

接下来,此数据加载到 DOM,以便可以在内存中使用它。 执行此操作的最常用方法是指向本地计算机上或在网络上的文件。

此示例从文件加载 XML。 如果文件不存在,它只需生成一些 XML,然后加载的。



Imports System
Imports System.Management


Public Class Sample
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Get the WMI class path
        Dim p As ManagementPath = _
            New ManagementPath( _
            "\\ComputerName\root" & _
            "\cimv2:Win32_LogicalDisk.DeviceID=""C:""")

        Console.WriteLine("IsClass: " & _
            p.IsClass)
        ' Should be False (because it is an instance)

        Console.WriteLine("IsInstance: " & _
            p.IsInstance)
        ' Should be True

        Console.WriteLine("ClassName: " & _
            p.ClassName)
        ' Should be "Win32_LogicalDisk"

        Console.WriteLine("NamespacePath: " & _
            p.NamespacePath)
        ' Should be "ComputerName\cimv2"

        Console.WriteLine("Server: " & _
            p.Server)
        ' Should be "ComputerName"

        Console.WriteLine("Path: " & _
            p.Path)
        ' Should be "ComputerName\root\cimv2:
        ' Win32_LogicalDisk.DeviceId="C:""

        Console.WriteLine("RelativePath: " & _
            p.RelativePath)
        ' Should be "Win32_LogicalDisk.DeviceID="C:""

    End Function
End Class

完整的示例︰Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:将 XML 文档读入 DOM

启动具有与此类似的 XML 架构。 此架构的 XML 中定义的数据类型并且需要哪些属性。

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www./2001/XMLSchema"
  attributeFormDefault="unqualified" 
  elementFormDefault="qualified"
  targetNamespace="http://www./books"> 
  <xs:element name="books">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="book">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:string" />
              <xs:element name="price" type="xs:decimal" />
            </xs:sequence>
            <xs:attribute name="genre" type="xs:string" use="required" />
            <xs:attribute name="ISBN" type="xs:string" use="required" />
            <xs:attribute name="publicationdate" type="xs:date" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

创建XmlReader使用您的架构对象,然后将该对象加载到 DOM 创建的事件处理程序执行当代码尝试修改的违反了架构的规则的方式将 XML 文件。

这些块的代码显示执行所有这些操作的帮助器方法。



'************************************************************************************
'
'  Associate the schema with XML. Then, load the XML and validate it against
'  the schema.
'
'************************************************************************************
Public Function LoadDocumentWithSchemaValidation(ByVal generateXML As Boolean, ByVal generateSchema As Boolean) As XmlDocument
    Dim reader As XmlReader
    Dim settings As XmlReaderSettings = New XmlReaderSettings
    ' Helper method to retrieve schema.
    Dim schema As XmlSchema = getSchema(generateSchema)
    If (schema Is Nothing) Then
        Return Nothing
    End If
    settings.Schemas.Add(schema)
    AddHandler settings.ValidationEventHandler, AddressOf settings_ValidationEventHandler
    settings.ValidationFlags = (settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings)
    settings.ValidationType = ValidationType.Schema
    Try
        reader = XmlReader.Create("booksData.xml", settings)
    Catch ex As System.IO.FileNotFoundException
        If generateXML Then
            Dim xml As String = generateXMLString()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xml)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            reader = XmlReader.Create(stream, settings)
        Else
            Return Nothing
        End If
    End Try
    Dim doc As XmlDocument = New XmlDocument
    doc.PreserveWhitespace = True
    doc.Load(reader)
    reader.Close()
    Return doc
End Function

'************************************************************************************
'
'  Helper method that generates an XML Schema.
'
'************************************************************************************
Private Function generateXMLSchema() As String

    Dim generatedXmlSchema As String = "<?xml version=""1.0"" encoding=""utf-8""?> " & _
            "<xs:schema attributeFormDefault=""unqualified"" " & _
            "elementFormDefault=""qualified"" targetNamespace=""http://www./books"" " & _
            "xmlns:xs=""http://www./2001/XMLSchema""> " & _
            "<xs:element name=""books""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element maxOccurs=""unbounded"" name=""book""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element name=""title"" type=""xs:string"" /> " & _
            "<xs:element name=""price"" type=""xs:decimal"" /> " & _
            "</xs:sequence> " & _
            "<xs:attribute name=""genre"" type=""xs:string"" use=""required"" /> " & _
            "<xs:attribute name=""publicationdate"" type=""xs:date"" use=""required"" /> " & _
            "<xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" /> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:sequence> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:schema> "


    Return generatedXmlSchema

End Function

'************************************************************************************
'
'  Helper method that gets a schema
'
'************************************************************************************
Private Function getSchema(ByVal generateSchema As Boolean) As XmlSchema
    Dim xs As XmlSchemaSet = New XmlSchemaSet
    Dim schema As XmlSchema
    Try
        schema = xs.Add("http://www./books", "booksData.xsd")
    Catch ex As System.IO.FileNotFoundException
        If generateSchema Then
            Dim xmlSchemaString As String = generateXMLSchema()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xmlSchemaString)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            Dim reader As XmlReader = XmlReader.Create(stream)
            schema = xs.Add("http://www./books", reader)
        Else
            Return Nothing
        End If
    End Try
    Return schema
End Function

'************************************************************************************
'
'  Helper method to validate the XML against the schema.
'
'************************************************************************************
Private Sub validateXML(ByVal generateSchema As Boolean, ByVal doc As XmlDocument)
    If (doc.Schemas.Count = 0) Then
        ' Helper method to retrieve schema.
        Dim schema As XmlSchema = getSchema(generateSchema)
        doc.Schemas.Add(schema)
    End If
    ' Use an event handler to validate the XML node against the schema.
    doc.Validate(AddressOf settings_ValidationEventHandler)
End Sub

'************************************************************************************
'
'  Event handler that is raised when XML doesn't validate against the schema.
'
'************************************************************************************
Private Sub settings_ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)
    If (e.Severity = XmlSeverityType.Warning) Then
        System.Windows.Forms.MessageBox.Show(("The following validation warning occurred: " & e.Message))
    ElseIf (e.Severity = XmlSeverityType.Error) Then
        System.Windows.Forms.MessageBox.Show(("The following critical validation errors occurred: " & e.Message))
        Dim objectType As Type = sender.GetType
    End If
End Sub

完整的示例︰Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:在 DOM 中验证 XML 文档

属性可用于浏览 XML 文档。 但在使用其中任何之前,让我们快速回顾了几个术语。 文档由组成节点。 每个节点都作为单紧靠它的上方的节点。 没有父节点的唯一节点是文档根,因为它是顶级节点。 大多数节点可以有是相邻的下一级的节点的节点。 位于相同级别的节点同级

下面的示例,演示如何获取根节点、 跳转到根节点的第一个子节点、 访问任何及其子节点、 连接返回到父节点中,和然后同级节点之间导航。

启动与根节点

此示例获取根节点,,然后使用该节点输出到控制台的文档的内容。



Option Strict
Option Explicit

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.LoadXml("<?xml version='1.0' ?>" & _
                    "<book genre='novel' ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "</book>")

        'Display the document element.
        Console.WriteLine(doc.DocumentElement.OuterXml)
    End Sub 'Main
End Class 'Sample

获取子节点

本示例跳转到根节点的第一个子节点,然后如果存在任何,循环访问该节点的子节点。



Option Strict
Option Explicit

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        'Display the contents of the child nodes.
        If root.HasChildNodes Then
            Dim i As Integer
            For i = 0 To root.ChildNodes.Count - 1
                Console.WriteLine(root.ChildNodes(i).InnerText)
            Next i
        End If
    End Sub 'Main
End Class 'Sample

回到父节点

使用 ParentNode 属性。

到最后一个引用的子节点

此示例将写入控制台 (这是 book 节点的最后一个子节点) 的一本书的价格。



Option Explicit
Option Strict

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        Console.WriteLine("Display the price element...")
        Console.WriteLine(root.LastChild.OuterXml)
    End Sub 'Main
End Class 'Sample

跨同级向前定位

此示例将向前移动簿工作簿。 书节点是同级到另一个。



Imports System
Imports System.Xml
Imports Microsoft.VisualBasic

public class Sample 

  public shared sub Main() 

      Dim doc as XmlDocument = new XmlDocument()
      doc.Load("books.xml")

      Dim currNode as XmlNode = doc.DocumentElement.FirstChild
      Console.WriteLine("First book...")
      Console.WriteLine(currNode.OuterXml)

      Dim nextNode as XmlNode = currNode.NextSibling
      Console.WriteLine(ControlChars.LF + "Second book...")
      Console.WriteLine(nextNode.OuterXml) 

  end sub
end class

向后导航跨同级

此示例将获取向后从簿工作簿。


Imports System
Imports System.Xml
Imports Microsoft.VisualBasic

public class Sample 

  public shared sub Main() 

      Dim doc as XmlDocument = new XmlDocument()
      doc.Load("books.xml")

      Dim lastNode as XmlNode = doc.DocumentElement.LastChild
      Console.WriteLine("Last book...")
      Console.WriteLine(lastNode.OuterXml)

      Dim prevNode as XmlNode = lastNode.PreviousSibling
      Console.WriteLine(ControlChars.LF + "Previous book...")
      Console.WriteLine(prevNode.OuterXml)  
  end sub
end class

若要查找的数据的一个或多个节点的最常用方法是使用 XPath 查询字符串,但也不需要一个的方法。

获取单个节点

此示例通过使用 ISBN 编号定位一本书。


Public Function GetBook(ByVal uniqueAttribute As String, ByVal doc As XmlDocument) As XmlNode
    Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
    nsmgr.AddNamespace("bk", "http://www./books")
    Dim xPathString As String = ("//bk:books/bk:book[@ISBN='" _
                & (uniqueAttribute & "']"))
    Dim xmlNode As XmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr)
    Return xmlNode
End Function

此示例中使用的字符串为 Xpath 查询。 你可以找到更多个示例︰ XPath examples

你还可以使用GetElementById检索节点。 若要使用此方法,你将需要定义 ID 文档类型定义声明的 XML 文件中。

获取节点后,你将收到的特性或子节点的值。 此示例将执行的与 book 节点。



Public Sub GetBookInformation(ByRef title As String, ByRef ISBN As String, ByRef publicationDate As String, ByRef price As String, ByRef genre As String, ByVal book As XmlNode)
    Dim bookElement As XmlElement = CType(book, XmlElement)
    ' Get the attributes of a book.        
    Dim attr As XmlAttribute = bookElement.GetAttributeNode("ISBN")
    ISBN = attr.InnerXml
    attr = bookElement.GetAttributeNode("genre")
    genre = attr.InnerXml
    attr = bookElement.GetAttributeNode("publicationdate")
    publicationDate = attr.InnerXml
    ' Get the values of child elements of a book.
    title = bookElement("title").InnerText
    price = bookElement("price").InnerText
End Sub

获取节点的集合

此示例选择的作者姓氏所在的所有丛书奥斯汀那个年代,然后将更改的这些图书的价格。



Imports System
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    'Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksort.xml")

    Dim book as XmlNode
    Dim nodeList as XmlNodeList 
    Dim root as XmlNode = doc.DocumentElement

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']")

    'Change the price on the books.
    for each book in nodeList      
      book.LastChild.InnerText="15.95"
    next 

    Console.WriteLine("Display the modified XML document....")
    doc.Save(Console.Out)

  end sub
end class

你可以使用节点的名称,以获取节点的集合。 例如,此示例将获取所有书名的集合。



Option Explicit
Option Strict

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.Load("books.xml")

        'Display all the book titles.
        Dim elemList As XmlNodeList = doc.GetElementsByTagName("title")
        Dim i As Integer
        For i = 0 To elemList.Count - 1
            Console.WriteLine(elemList(i).InnerXml)
        Next i
    End Sub 'Main 
End Class 'Sample

完整的示例︰Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:使用 XPath 导航选择节点

此示例通过编辑 book 节点和其属性。



Public Sub editBook(ByVal title As String, ByVal ISBN As String,
                    ByVal publicationDate As String, ByVal genre As String,
                    ByVal price As String, ByVal book As XmlNode, ByVal validateNode As Boolean,
                    ByVal generateSchema As Boolean)

    Dim bookElement As XmlElement = CType(book, XmlElement)

    ' Get the attributes of a book.        
    bookElement.SetAttribute("ISBN", ISBN)
    bookElement.SetAttribute("genre", genre)
    bookElement.SetAttribute("publicationdate", publicationDate)

    ' Get the values of child elements of a book.
    bookElement("title").InnerText = title
    bookElement("price").InnerText = price
    If validateNode Then
        validateXML(generateSchema, bookElement.OwnerDocument)
    End If

End Sub

了解更多信息:修改 XML 文档中的节点、内容和值

完整的示例︰Manipulate XML in-Memory by using the XmlDocument class and other related types

若要添加节点时,使用CreateElement方法或CreateNode方法。

若要添加数据节点,如一本书,使用CreateElement方法。

对于任何其他类型的节点,例如注释、 空白节点或 CDATA 节点,使用CreateNode方法。

此示例创建 book 节点,将 attrubutes 添加到该节点,然后将该节点添加到文档。



Public Function AddNewBook(ByVal genre As String, ByVal ISBN As String, ByVal misc As String, ByVal title As String, ByVal price As String, ByVal doc As XmlDocument) As XmlElement
    ' Create a new book element.
    Dim bookElement As XmlElement = doc.CreateElement("book", "http://www./books")

    ' Create attributes for book and append them to the book element.
    Dim attribute As XmlAttribute = doc.CreateAttribute("genre")
    attribute.Value = genre
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("ISBN")
    attribute.Value = ISBN
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("publicationdate")
    attribute.Value = misc
    bookElement.Attributes.Append(attribute)

    ' Create and append a child element for the title of the book.
    Dim titleElement As XmlElement = doc.CreateElement("title")
    titleElement.InnerText = title
    bookElement.AppendChild(titleElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(titleElement.OuterXml, _
                           "\n   " & titleElement.OuterXml & " " & ControlChars.NewLine + "    ")
    ' Create and append a child element for the price of the book.
    Dim priceElement As XmlElement = doc.CreateElement("price")
    priceElement.InnerText = price
    bookElement.AppendChild(priceElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(priceElement.OuterXml,
                                                        (priceElement.OuterXml & "   " & ControlChars.NewLine & "  "))
    Return bookElement
End Function

完整的示例︰Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:将节点插入 XML 文档中

若要删除节点,使用RemoveChild方法。

此示例从文档和之前 book 节点将显示任何空格删除一本书。



Public Sub deleteBook(ByVal book As XmlNode)

    Dim prevNode As XmlNode = book.PreviousSibling
    book.OwnerDocument.DocumentElement.RemoveChild(book)

    If ((prevNode.NodeType = XmlNodeType.Whitespace) _
                OrElse (prevNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
        prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode)

    End If
End Sub

完整的示例︰Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:移除 XML 文档中的节点、内容和值

你可以选择想要通过使用显示在文档中的节点InsertBeforeInsertAfter方法。

此示例演示两个帮助器方法。 其中一个将更高版本的节点列表中。 较低的节点移动另一个。

应用程序,使用户能够在的书籍的列表中向上和向下移动丛书中,可以使用这些方法。 当用户选择一本书并按下向上或向下按钮时,你的代码无法调用这些位置相应的 book 节点之前或之后其他 book 节点等方法。



'************************************************************************************
'
'  Summary: Move elements up in the XML.
'  
'
'************************************************************************************
Public Sub MoveElementUp(ByVal book As XmlNode)
    Dim previousNode As XmlNode = book.PreviousSibling

    While ((Not (previousNode) Is Nothing) _
                AndAlso (previousNode.NodeType <> XmlNodeType.Element))
        previousNode = previousNode.PreviousSibling

    End While
    If (Not (previousNode) Is Nothing) Then
        Dim newLineNode As XmlNode = book.NextSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionAbove,
                          previousNode, False, False)
    End If
End Sub

'************************************************************************************
'
'  Summary: Move elements down in the XML.
'  
'
'************************************************************************************
Public Sub MoveElementDown(ByVal book As XmlNode)
    ' Walk backwards until we find an element - ignore text nodes
    Dim NextNode As XmlNode = book.NextSibling

    While ((Not (NextNode) Is Nothing) _
                AndAlso (NextNode.NodeType <> XmlNodeType.Element))
        NextNode = NextNode.NextSibling

    End While

    If (Not (NextNode) Is Nothing) Then
        Dim newLineNode As XmlNode = book.PreviousSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionBelow,
                          NextNode, False, False)
    End If
End Sub
完整的示例︰Manipulate XML in-Memory by using the XmlDocument class and other related types


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多