📜  VB.Net-XML处理

📅  最后修改于: 2020-11-19 09:05:21             🧑  作者: Mango


可扩展标记语言(XML)是一种类似于HTML或SGML的标记语言。万维网联盟建议这样做,并且可以作为开放标准使用。

.Net Framework中的System.Xml命名空间包含用于处理XML文档的类。以下是System.Xml命名空间中的一些常用类。

Sr.No. Class & Description
1

XmlAttribute

Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.

2

XmlCDataSection

Represents a CDATA section.

3

XmlCharacterData

Provides text manipulation methods that are used by several classes.

4

XmlComment

Represents the content of an XML comment.

5

XmlConvert

Encodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types, the values returned are locale independent.

6

XmlDeclaration

Represents the XML declaration node .

7

XmlDictionary

Implements a dictionary used to optimize Windows Communication Foundation (WCF)’s XML reader/writer implementations.

8

XmlDictionaryReader

An abstract class that the Windows Communication Foundation (WCF) derives from XmlReader to do serialization and deserialization.

9

XmlDictionaryWriter

Represents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter to do serialization and deserialization.

10

XmlDocument

Represents an XML document.

11

XmlDocumentFragment

Represents a lightweight object that is useful for tree insert operations.

12

XmlDocumentType

Represents the document type declaration.

13

XmlElement

Represents an element.

14

XmlEntity

Represents an entity declaration, such as .

15

XmlEntityReference

Represents an entity reference node.

16

XmlException

Returns detailed information about the last exception.

17

XmlImplementation

Defines the context for a set of XmlDocument objects.

18

XmlLinkedNode

Gets the node immediately preceding or following this node.

19

XmlNode

Represents a single node in the XML document.

20

XmlNodeList

Represents an ordered collection of nodes.

21

XmlNodeReader

Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode.

22

XmlNotation

Represents a notation declaration, such as .

23

XmlParserContext

Provides all the context information required by the XmlReader to parse an XML fragment.

24

XmlProcessingInstruction

Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document.

25

XmlQualifiedName

Represents an XML qualified name.

26

XmlReader

Represents a reader that provides fast, noncached, forward-only access to XML data.

27

XmlReaderSettings

Specifies a set of features to support on the XmlReader object created by the Create method.

28

XmlResolver

Resolves external XML resources named by a Uniform Resource Identifier (URI).

29

XmlSecureResolver

Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to.

30

XmlSignificantWhitespace

Represents white space between markup in a mixed content node or white space within an xml:space= ‘preserve’ scope. This is also referred to as significant white space.

31

XmlText

Represents the text content of an element or attribute.

32

XmlTextReader

Represents a reader that provides fast, non-cached, forward-only access to XML data.

33

XmlTextWriter

Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

34

XmlUrlResolver

Resolves external XML resources named by a Uniform Resource Identifier (URI).

35

XmlWhitespace

Represents white space in element content.

36

XmlWriter

Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.

37

XmlWriterSettings

Specifies a set of features to support on the XmlWriter object created by the XmlWriter.Create method.

XML解析器API

SAX和DOM接口是两个最基本且使用最广泛的XML数据API。

  • XML的简单API(SAX) -在这里,您注册感兴趣事件的回调,然后让解析器继续处理文档。当您的文档很大或有内存限制时,此功能非常有用,它会在从磁盘读取文件时解析该文件,并且整个文件永远不会存储在内存中。

  • 文档对象模型(DOM)API-这是万维网联盟的建议,其中,将整个文件读入内存并以分层(基于树)的形式存储,以表示XML文档的所有功能。

当处理大文件时,SAX显然无法像DOM一样快地处理信息。另一方面,仅使用DOM确实可以杀死您的资源,尤其是在许多小文件上使用时。

SAX是只读的,而DOM允许更改XML文件。由于这两个不同的API实际上相互补充,因此没有理由不能在大型项目中同时使用它们。

对于我们所有的XML代码示例,让我们使用一个简单的XML文件movie.xml作为输入-




   
      War, Thriller
      DVD
      2003
      PG
      10
      Talk about a US-Japan war
   

   
      Anime, Science Fiction
      DVD
      1989
      R
      8
      A schientific fiction
   

   
      Anime, Action
      DVD
      4
      PG
      10
      Vash the Stampede!
   

   
      Comedy
      VHS
      PG
      2
      Viewable boredom
   

使用SAX API解析XML

在SAX模型中,可以使用XmlReaderXmlWriter类来处理XML数据。

XmlReader类用于以快速,仅转发和非缓存的方式读取XML数据。它读取XML文档或流。

例子1

本示例演示了如何从movie.xml文件读取XML数据。

采取以下步骤-

  • 将movie.xml文件添加到应用程序的bin \ Debug文件夹中。

  • 在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 = "tutorialspoint.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

使用Microsoft Visual Studio工具栏上的“开始”按钮执行并运行上述代码。单击按钮将显示文件中电影的标题,类型和描述。

VB.Net XML处理示例1

XmlWriter类用于将XML数据写入流,文件或TextWriter对象。它还以仅转发,非缓存的方式工作。

例子2

让我们通过在运行时添加一些数据来创建XML文件。采取以下步骤-

  • 在表单中添加一个WebBrowser控件和一个按钮控件。

  • 将按钮的“文本”属性更改为“显示作者文件”。

  • 在代码编辑器中添加以下代码。

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 = "tutorialspoint.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", "Zara")
      xw.WriteElementString("lname", "Ali")
      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
  • 使用Microsoft Visual Studio工具栏上的“开始”按钮执行并运行上述代码。单击“显示作者文件”将在网络浏览器上显示新创建的authors.xml文件。

VB.Net XML处理示例2

使用DOM API解析XML

根据文档对象模型(DOM),XML文档由节点和节点属性组成。 XmlDocument类用于实现.Net Framework的XML DOM解析器。它还允许您通过在文档中插入,删除或更新数据来修改现有的XML文档。

以下是XmlDocument类的一些常用方法-

Sr.No. Method Name & Description
1

AppendChild

Adds the specified node to the end of the list of child nodes, of this node.

2

CreateAttribute(String)

Creates an XmlAttribute with the specified Name.

3

CreateComment

Creates an XmlComment containing the specified data.

4

CreateDefaultAttribute

Creates a default attribute with the specified prefix, local name and namespace URI.

5

CreateElement(String)

Creates an element with the specified name.

6

CreateNode(String, String, String)

Creates an XmlNode with the specified node type, Name, and NamespaceURI.

7

CreateNode(XmlNodeType, String, String)

Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.

8

CreateNode(XmlNodeType, String, String, String)

Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.

9

CreateProcessingInstruction

Creates an XmlProcessingInstruction with the specified name and data.

10

CreateSignificantWhitespace

Creates an XmlSignificantWhitespace node.

11

CreateTextNode

Creates an XmlText with the specified text.

12

CreateWhitespace

Creates an XmlWhitespace node.

13

CreateXmlDeclaration

Creates an XmlDeclaration node with the specified values.

14

GetElementById

Gets the XmlElement with the specified ID.

15

GetElementsByTagName(String)

Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.

16

GetElementsByTagName(String, String)

Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.

17

InsertAfter

Inserts the specified node immediately after the specified reference node.

18

InsertBefore

Inserts the specified node immediately before the specified reference node.

19

Load(Stream)

Loads the XML document from the specified stream.

20

Load(String)

Loads the XML document from the specified URL.

21

Load(TextReader)

Loads the XML document from the specified TextReader.

22

Load(XmlReader)

Loads the XML document from the specified XmlReader.

23

LoadXml

Loads the XML document from the specified string.

24

PrependChild

Adds the specified node to the beginning of the list of child nodes for this node.

25

ReadNode

Creates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute.

26

RemoveAll

Removes all the child nodes and/or attributes of the current node.

27

RemoveChild

Removes specified child node.

28

ReplaceChild

Replaces the child node oldChild with newChild node.

29

Save(Stream)

Saves the XML document to the specified stream.

30

Save(String)

Saves the XML document to the specified file.

31

Save(TextWriter)

Saves the XML document to the specified TextWriter.

32

Save(XmlWriter)

Saves the XML document to the specified XmlWriter.

例子3

在此示例中,让我们在xml文档authors.xml中插入一些新节点,然后在列表框中显示所有作者的名字。

采取以下步骤-

  • 将authors.xml文件添加到应用程序的bin / Debug文件夹中(如果您尝试了最后一个示例,则该文件应该在该文件夹中)

  • 导入System.Xml命名空间

  • 在窗体中添加一个列表框和一个按钮控件,并将该按钮控件的text属性设置为Show Authors。

  • 使用代码编辑器添加以下代码。

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 = "tutorialspoint.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
  • 使用Microsoft Visual Studio工具栏上的“开始”按钮执行并运行上述代码。单击“显示作者”按钮将显示所有作者的名字,包括我们在运行时添加的名字。

VB.Net XML处理示例3