可擴展標記語言(XML)是一種非常類似於HTML或SGML的標記語言。這是由萬維網聯盟推薦的,可作為開放標準提供。
.Net Framework中的System.Xml
命名空間包含用於處理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介面。
- 簡單的XML(SAX)API:在這裏,只為感興趣的事件註冊回調,然後讓解析器繼續處理文檔。 當文檔很大或者記憶體有限制時,這是非常有用的,它在從磁片讀取檔時解析檔,整個檔永遠不會存儲在內存中。
- 文檔對象模型(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模型中,使用XmlReader
和XmlWriter
類來處理XML數據。XmlReader
類用於以快速,只進和非緩存的方式讀取XML數據。它讀取一個XML文檔或一個流。
示例1
這個例子演示了從檔movies.xml
中讀取XML數據。
- 在應用程式的
bin\Debug
檔夾中添加movies.xml
檔。 - 在
Form1.vb
檔中導入System.Xml
名稱空間。 - 在窗體中添加一個標籤,並將其文本更改為“電影列表”。
- 添加三個列表框和三個按鈕,以顯示來自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 = "SAX API讀取XML示例1 - xuhuhu.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工具欄上的“開始”按鈕執行並運行上述代碼。 點擊按鈕將顯示檔的標題,類型和電影描述。
分別點擊下麵的幾個按鈕來加載movies.xml 檔中的對應內容 -
XmlWriter
類用於將XML數據寫入流,檔或TextWriter
對象。它也以只向前,非緩存的方式工作。
示例2
這個示例中是通過在運行時添加一些數據來創建一個XML檔。參考以下步驟:
- 在窗體中添加一個
WebBrowser
控件和一個按鈕(Button
)控件。 - 將該按鈕的Text屬性更改為顯示作者檔。
在代碼編輯器中添加下麵的代碼 -
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 = "寫入XML檔 - xuhuhu.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", "Su")
xw.WriteElementString("lname", "Max")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "2")
xw.WriteElementString("fname", "Paul")
xw.WriteElementString("lname", "Sharma")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "3")
xw.WriteElementString("fname", "Anshuman")
xw.WriteElementString("lname", "Curry")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "4")
xw.WriteElementString("fname", "張")
xw.WriteElementString("lname", "愛玲")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "5")
xw.WriteElementString("fname", "蘇")
xw.WriteElementString("lname", "琴")
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工具欄上的“開始”按鈕執行並運行上述代碼。 單擊顯示作者檔將在Web流覽器上顯示新創建的authors.xml
檔。運行結果如下圖所示 -
點擊顯示作者檔內容,看到以下結果 -
用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) |
用指定的節點類型,名稱和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 |
獲取具有指定標識的XmlElement 。 |
15 | GetElementsByTagName(String) |
返回一個XmlNodeList ,其中包含與指定的Name 匹配的所有子元素的列表。 |
16 | GetElementsByTagName(String, String) |
返回包含與指定的LocalName 和NamespaceURI 匹配的所有子元素的列表的XmlNodeList 。 |
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 |
用newChild 節點替換子節點oldChild 。 |
29 | Save(Stream) |
將XML文檔保存到指定的流。 |
30 | Save(String) |
將XML文檔保存到指定的檔。 |
31 | Save(TextWriter) |
將XML文檔保存到指定的TextWriter 。 |
32 | Save(XmlWriter) |
將XML文檔保存到指定的XmlWriter 。 |
示例3
在這個例子中,將向xml文檔authors.xml
中插入一些新節點,然後在列表框中顯示所有作者的名字。
參考以下步驟:
- 將authors.xml 檔添加到應用程式的 bin/Debug 檔夾中(如果已經編寫上示例2,那麼應該在示例2工程中生成了)
- 導入System.Xml名稱空間
- 在窗體中添加一個列表框和按鈕控件,並將按鈕控件的
Text
屬性設置為顯示作者。
使用代碼編輯器添加以下代碼。參考代碼實現 -
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 = "插入XML節點 - xuhuhu.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 = "李"
newAuthor.AppendChild(fn)
Dim ln As XmlElement = xd.CreateElement("lname")
ln.InnerText = "安"
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("lname")
For Each node As XmlNode In nl
ListBox1.Items.Add(node.InnerText)
Next node
End Sub
End Class
使用Microsoft Visual Studio工具欄上的“開始”按鈕執行並運行上述代碼。點擊顯示作者 按鈕將顯示所有作者的名字,包括在運行時添加的名字。
點擊按鈕後的效果如下所示 -