將 XML 文件讀取到 DOMReading an XML Document into the DOM

從不同的格式將 XML 資訊讀取到記憶體。XML information is read into memory from different formats. 可從字串、資料流、URL、文字讀取器或衍生自 XmlReader 的類別讀取它。It can be read from a string, stream, URL, text reader, or a class derived from the XmlReader.

Load 方法將文件引入記憶體,並擁有可從各個不同格式取得資料的多載方法。The Load method brings the document into memory and has overloaded methods available to take data from each of the different formats. 另外還有一個 LoadXml 方法,可從字串讀取 XML。There is also a LoadXml method that reads XML from a string.

不同的 Load 方法會影響載入 XML 文件物件模型 (DOM) 時建立的節點。Different Load methods affect which nodes are created when the XML Document Object Model (DOM) is loaded. 下表列出某些 Load 方法及說明這些方法之主題間的差異。The following table lists the differences between some of the Load methods and topics that address them.

主旨Subject 主題Topic
建立泛空白字元節點Creation of white space nodes 用來載入 DOM 的物件會影響在 DOM 中產生的泛空白字元及顯著泛空白字元節點。The object used to load the DOM has an affect on the white space and significant white space nodes generated in the DOM. 如需詳細資訊,請參閱載入 DOM 時處理泛空白字元和顯著泛空白字元For more information, see White Space and Significant White Space Handling when Loading the DOM.
從特定節點開始載入 XML 或載入整個 XML 文件Loading XML starting from a specific node or loading the entire XML document 使用 XmlDocument.Load 方法可將資料從特定節點載入至 DOM。Using the XmlDocument.Load method data can be loaded from a specific node into the DOM. 如需詳細資訊,請參閱從讀取器載入資料For more information, see Load Data from a Reader.
載入 XML 時進行驗證Validating the XML as it is loaded 可在將 XML 資料載入至 DOM 時對其進行驗證。The XML data loaded into the DOM can be validated as it is loaded. 使用驗證 XmlReader 來完成此作業。This is accomplished using a validating XmlReader. 如需在載入 XML 時進行驗證的詳細資訊,請參閱驗證 DOM 中的 XML 文件For more information about validating XML as it is loaded, see Validating an XML Document in the DOM.

下列範例顯示以 LoadXml 方法載入的 XML,以及隨後儲存至稱為 data.xml 之文字檔的資料。The following example shows XML being loaded with the LoadXml method and the data subsequently saved to a text file called data.xml.

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(("<book genre='novel' ISBN='1-861001-57-5'>" & _  
                    "<title>Pride And Prejudice</title>" & _  
                    "</book>"))  
        ' Save the document to a file.  
        doc.Save("data.xml")  
    End Sub 'Main  
End Class 'Sample  
using System;  
using System.IO;  
using System.Xml;  
  
public class Sample  
{  
    public static void Main()  
    {  
        // Create the XmlDocument.  
        XmlDocument doc = new XmlDocument();  
        doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +  
                    "<title>Pride And Prejudice</title>" +  
                    "</book>");  
  
        // Save the document to a file.  
        doc.Save("data.xml");  
    }  
}  

另請參閱See also