System.Xml.XmlDocument 類別
本文提供此 API 參考文件的補充備註。
類別 XmlDocument 是 XML 檔的記憶體內部表示法。 它會實作 W3C XML 檔物件模型 (DOM) 層級 1 核心和核心 DOM 層級 2。
DOM 代表 文件物件模型。 若要深入瞭解,請參閱 XML 檔物件模型(DOM)。
您可以使用 類別將 XML 載入 DOM XmlDocument ,然後以程式設計方式讀取、修改和移除檔中的 XML。
如果您想要擷取開啟 XmlDocument 類別,並查看其實作方式,請參閱 參考來源。
將 XML 載入檔案物件模型
從類似此的 XML 檔開始,其中包含一些集合中的書籍。 其中包含您在任何 XML 檔中找到的基本專案,包括命名空間、代表數據的元素,以及描述數據的屬性。
<?xml version="1.0" encoding="utf-8"?>
<books xmlns="http://www.contoso.com/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 並載入該檔案。
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
try { doc.Load("booksData.xml"); }
catch (System.IO.FileNotFoundException)
{
doc.LoadXml("<?xml version=\"1.0\"?> \n" +
"<books xmlns=\"http://www.contoso.com/books\"> \n" +
" <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
" <title>Pride And Prejudice</title> \n" +
" <price>24.95</price> \n" +
" </book> \n" +
" <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
" <title>The Handmaid's Tale</title> \n" +
" <price>29.95</price> \n" +
" </book> \n" +
"</books>");
}
Dim doc As XmlDocument = New XmlDocument
doc.PreserveWhitespace = True
Try
doc.Load("booksData.xml")
Catch ex As System.IO.FileNotFoundException
' If no file is found, generate some XML.
doc.LoadXml("<?xml version=""1.0""?> " & ControlChars.NewLine & _
"<books xmlns=""http://www.contoso.com/books""> " & ControlChars.NewLine & _
" <book genre=""novel"" ISBN=""1-861001-57-8"" publicationdate=""1823-01-28""> " & ControlChars.NewLine & _
" <title>Pride And Prejudice</title> " & ControlChars.NewLine & _
" <price>24.95</price> " & ControlChars.NewLine & _
" </book> " & ControlChars.NewLine & _
" <book genre=""novel"" ISBN=""1-861002-30-1"" publicationdate=""1985-01-01""> " & ControlChars.NewLine & _
" <title>The Handmaid's Tale</title> " & ControlChars.NewLine & _
" <price>29.95</price> " & ControlChars.NewLine & _
" </book> " & ControlChars.NewLine & _
"</books>")
End Try
如需詳細資訊,請參閱 將 XML 檔讀入 DOM。
針對架構進行驗證
從 XML 架構開始,如下所示。 此架構會定義 XML 中的數據類型,以及需要哪些屬性。
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
attributeFormDefault="unqualified"
elementFormDefault="qualified"
targetNamespace="http://www.contoso.com/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 檔案時執行。
這些程式代碼區塊會顯示執行上述所有動作的協助程式方法。
//************************************************************************************
//
// Helper method that generates an XML string.
//
//************************************************************************************
private string generateXMLString()
{
string xml = "<?xml version=\"1.0\"?> \n" +
"<books xmlns=\"http://www.contoso.com/books\"> \n" +
" <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
" <title>Pride And Prejudice</title> \n" +
" <price>24.95</price> \n" +
" </book> \n" +
" <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
" <title>The Handmaid's Tale</title> \n" +
" <price>29.95</price> \n" +
" </book> \n" +
" <book genre=\"novel\" ISBN=\"1-861001-45-3\" publicationdate=\"1811-01-01\"> \n" +
" <title>Sense and Sensibility</title> \n" +
" <price>19.95</price> \n" +
" </book> \n" +
"</books>";
return xml;
}
//************************************************************************************
//
// Associate the schema with XML. Then, load the XML and validate it against
// the schema.
//
//************************************************************************************
public XmlDocument LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
XmlReader reader = null;
XmlReaderSettings settings = new XmlReaderSettings();
// Helper method to retrieve schema.
XmlSchema schema = getSchema(generateSchema);
settings.Schemas.Add(schema);
settings.ValidationEventHandler += ValidationCallback;
settings.ValidationFlags =
settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationType = ValidationType.Schema;
if (!generateXML)
{
try
{
reader = XmlReader.Create("booksData.xml", settings);
}
catch (FileNotFoundException ex)
{
Console.WriteLine(
$"XML file not found so generating: {ex.Message}");
generateXML = true;
}
}
if (generateXML)
{
string xml = generateXMLString();
StringReader stringReader = new StringReader(xml);
reader = XmlReader.Create(stringReader, settings);
}
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(reader);
reader.Close();
return doc;
}
//************************************************************************************
//
// Helper method that generates an XML Schema.
//
//************************************************************************************
private string generateXMLSchema()
{
string xmlSchema =
"<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
"<xs:schema attributeFormDefault=\"unqualified\" " +
"elementFormDefault=\"qualified\" targetNamespace=\"http://www.contoso.com/books\" " +
"xmlns:xs=\"http://www.w3.org/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 xmlSchema;
}
//************************************************************************************
//
// Helper method that gets a schema
//
//************************************************************************************
private XmlSchema getSchema(bool generateSchema)
{
XmlSchemaSet xs = new XmlSchemaSet();
XmlSchema schema = null;
if (!generateSchema)
{
try
{
schema = xs.Add("http://www.contoso.com/books", "booksData.xsd");
}
catch (FileNotFoundException ex)
{
Console.WriteLine(
$"XSD file not found so generating: {ex.Message}");
generateSchema = true;
}
}
if (generateSchema)
{
string xmlSchemaString = generateXMLSchema();
StringReader stringReader = new StringReader(xmlSchemaString);
XmlReader reader = XmlReader.Create(stringReader);
schema = xs.Add("http://www.contoso.com/books", reader);
}
return schema;
}
//************************************************************************************
//
// Helper method to validate the XML against the schema.
//
//************************************************************************************
private void validateXML(bool generateSchema, XmlDocument doc)
{
if (doc.Schemas.Count == 0)
{
// Helper method to retrieve schema.
XmlSchema schema = getSchema(generateSchema);
doc.Schemas.Add(schema);
}
// Use a callback to validate the XML node against the schema.
doc.Validate(ValidationCallback);
}
//************************************************************************************
//
// Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************
void ValidationCallback(object sender,
System.Xml.Schema.ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning)
{
Console.WriteLine
("The following validation warning occurred: " + e.Message);
}
else if (e.Severity == XmlSeverityType.Error)
{
Console.WriteLine
("The following critical validation errors occurred: " + e.Message);
}
}
'************************************************************************************
'
' 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.contoso.com/books"" " & _
"xmlns:xs=""http://www.w3.org/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.contoso.com/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.contoso.com/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
如需詳細資訊,請參閱 在 DOM 中驗證 XML 檔。
瀏覽檔案樹狀結構
您可以使用屬性來巡覽 XML 檔。 但在您使用其中任何一個字詞之前,讓我們快速檢閱幾個詞彙。 您的檔是由節點所組成。 每個節點都有一個直接位於其上方的單 一父 節點。 沒有父節點的唯一節點是檔根目錄,因為它是最上層節點。 大部分節點都可以有 子 節點,也就是它們正下方的節點。 位於相同層級的節點為 同層級。
下列範例示範如何取得根節點、跳至根節點的第一個子節點、存取其任何子節點、返回父節點,然後流覽至同層級節點。
從根節點開始
這個範例會取得根節點,然後使用該節點將檔的內容輸出至主控台。
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
//Create the XmlDocument.
XmlDocument doc = 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);
}
}
Option Strict On
Option Explicit On
Imports System.Xml
Public Class ElementSample
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
End Class
取得子節點
本範例會跳至根節點的第一個子節點,然後逐一查看該節點的子節點,如果有的話。
using System;
using System.Xml;
public class Sample2
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"<price>19.95</price>" +
"</book>");
XmlNode root = doc.FirstChild;
//Display the contents of the child nodes.
if (root.HasChildNodes)
{
for (int i = 0; i < root.ChildNodes.Count; i++)
{
Console.WriteLine(root.ChildNodes[i].InnerText);
}
}
}
}
Option Strict
Option Explicit
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
End Class
回到父節點
請使用 ParentNode 屬性。
請參閱最後一個子節點
本範例會將書籍的價格寫入主控台。 價格節點是書籍節點的最後一個子系。
using System;
using System.Xml;
public class Sample3
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"<price>19.95</price>" +
"</book>");
XmlNode root = doc.FirstChild;
Console.WriteLine("Display the price element...");
Console.WriteLine(root.LastChild.OuterXml);
}
}
Option Explicit On
Option Strict On
Imports System.Xml
Public Class LastChildSample
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
End Class
在同層級之間向前巡覽
本範例會從書籍往前移動。 書籍節點是彼此的同層級節點。
using System;
using System.Xml;
public class Sample4
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlNode currNode = doc.DocumentElement.FirstChild;
Console.WriteLine("First book...");
Console.WriteLine(currNode.OuterXml);
XmlNode nextNode = currNode.NextSibling;
Console.WriteLine("\r\nSecond book...");
Console.WriteLine(nextNode.OuterXml);
}
}
Imports System.Xml
Public Class NextSiblingSample
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
在同層級之間向後巡覽
本範例會從書籍向後移動。
using System;
using System.Xml;
public class Sample {
public static void Main() {
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlNode lastNode = doc.DocumentElement.LastChild;
Console.WriteLine("Last book...");
Console.WriteLine(lastNode.OuterXml);
XmlNode prevNode = lastNode.PreviousSibling;
Console.WriteLine("\r\nPrevious book...");
Console.WriteLine(prevNode.OuterXml);
}
}
Imports System.Xml
Public Class Sample5
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 XmlNode GetBook(string uniqueAttribute, XmlDocument doc)
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "http://www.contoso.com/books");
string xPathString = "//bk:books/bk:book[@ISBN='" + uniqueAttribute + "']";
XmlNode xmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr);
return xmlNode;
}
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.contoso.com/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 範例中找到更多 範例。
您也可以使用 GetElementById 來擷取節點。 若要使用此方法,您必須在 XML 檔案的檔案類型定義宣告中定義識別碼。
取得節點之後,您會取得屬性或子節點的值。 此範例會使用書籍節點執行此動作。
public void GetBookInformation(ref string title, ref string ISBN, ref string publicationDate,
ref string price, ref string genre, XmlNode book)
{
XmlElement bookElement = (XmlElement)book;
// Get the attributes of a book.
XmlAttribute attr = 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;
}
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
取得節點的集合
本範例會選取作者姓氏為 Austen 的所有書籍,然後變更這些書籍的價格。
using System;
using System.Xml;
public class Sample6
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("descendant::book[author/last-name='Austen']");
//Change the price on the books.
foreach (XmlNode book in nodeList)
{
book.LastChild.InnerText = "15.95";
}
Console.WriteLine("Display the modified XML document....");
doc.Save(Console.Out);
}
}
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
您也可以使用節點的名稱來取得節點集合。 例如,這個範例會取得所有書名的集合。
using System;
using System.Xml;
public class Sample1
{
public static void Main()
{
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
//Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");
for (int i = 0; i < elemList.Count; i++)
{
Console.WriteLine(elemList[i].InnerXml);
}
}
}
Option Explicit On
Option Strict On
Imports System.Xml
Public Class TagSample
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
End Class
如需詳細資訊,請參閱 使用 XPath 瀏覽選取節點。
編輯節點
本範例會編輯書籍節點及其屬性。
public void editBook(string title, string ISBN, string publicationDate,
string genre, string price, XmlNode book, bool validateNode, bool generateSchema)
{
XmlElement bookElement = (XmlElement)book;
// 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)
{
validateXML(generateSchema, bookElement.OwnerDocument);
}
}
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 檔中的節點、內容和值。
新增節點
若要新增節點,請使用 CreateElement 方法或 CreateNode 方法。
若要新增數據節點,例如書籍,請使用 CreateElement 方法。
對於任何其他類型的節點,例如批注、空格符節點或 CDATA 節點,請使用 CreateNode 方法。
本範例會建立書籍節點、將屬性新增至該節點,然後將該節點新增至檔。
public XmlElement AddNewBook(string genre, string ISBN, string misc,
string title, string price, XmlDocument doc)
{
// Create a new book element.
XmlElement bookElement = doc.CreateElement("book", "http://www.contoso.com/books");
// Create attributes for book and append them to the book element.
XmlAttribute attribute = 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.
XmlElement titleElement = 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 + " \n ");
// Create and append a child element for the price of the book.
XmlElement priceElement = 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 + " \n ");
return bookElement;
}
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.contoso.com/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
如需詳細資訊,請參閱 將節點插入 XML 檔中。
拿掉節點
若要移除節點,請使用 RemoveChild 方法。
本範例會從檔中移除書籍,以及出現在書籍節點之前的任何空格符。
public void deleteBook(XmlNode book)
{
XmlNode prevNode = book.PreviousSibling;
book.OwnerDocument.DocumentElement.RemoveChild(book);
if (prevNode.NodeType == XmlNodeType.Whitespace ||
prevNode.NodeType == XmlNodeType.SignificantWhitespace)
{
prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode);
}
}
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
如需詳細資訊,請參閱 從 XML 檔移除節點、內容和值。
定位節點
您可以使用 和 InsertAfter 方法,選擇您希望節點出現在檔中InsertBefore的位置。
此範例顯示兩個協助程式方法。 其中一個會在清單中將節點往上移動。 另一個節點會往下移動。
這些方法可用於可讓使用者在書籍清單中上下移動書籍的應用程式中。 當使用者選擇書籍並按下向上或向下按鈕時,您的程式代碼可以呼叫這類方法,以在其他書籍節點之前或之後放置對應的書籍節點。
//************************************************************************************
//
// Summary: Move elements up in the XML.
//
//
//************************************************************************************
public void MoveElementUp(XmlNode book)
{
XmlNode previousNode = book.PreviousSibling;
while (previousNode != null && (previousNode.NodeType != XmlNodeType.Element))
{
previousNode = previousNode.PreviousSibling;
}
if (previousNode != null)
{
XmlNode newLineNode = book.NextSibling;
book.OwnerDocument.DocumentElement.RemoveChild(book);
if (newLineNode.NodeType == XmlNodeType.Whitespace |
newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
{
newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
}
InsertBookElement((XmlElement)book, Constants.positionAbove,
previousNode, false, false);
}
}
//************************************************************************************
//
// Summary: Move elements down in the XML.
//
//
//************************************************************************************
public void MoveElementDown(XmlNode book)
{
// Walk backwards until we find an element - ignore text nodes
XmlNode NextNode = book.NextSibling;
while (NextNode != null && (NextNode.NodeType != XmlNodeType.Element))
{
NextNode = NextNode.NextSibling;
}
if (NextNode != null)
{
XmlNode newLineNode = book.PreviousSibling;
book.OwnerDocument.DocumentElement.RemoveChild(book);
if (newLineNode.NodeType == XmlNodeType.Whitespace |
newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
{
newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
}
InsertBookElement((XmlElement)book, Constants.positionBelow,
NextNode, false, false);
}
}
'************************************************************************************
'
' 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