XmlDocument.Load 方法

定义

Stream、URL、TextReaderXmlReader 加载指定的 XML 数据。Loads the specified XML data from a Stream, a URL, a TextReader, or an XmlReader.

重载

Load(Stream)

从指定的流加载 XML 文档。Loads the XML document from the specified stream.

Load(TextReader)

从指定的 TextReader 加载 XML 文档。Loads the XML document from the specified TextReader.

Load(String)

从指定的 URL 加载 XML 文档。Loads the XML document from the specified URL.

Load(XmlReader)

从指定的 XmlReader 加载 XML 文档。Loads the XML document from the specified XmlReader.

Load(Stream)

从指定的流加载 XML 文档。Loads the XML document from the specified stream.

public:
 virtual void Load(System::IO::Stream ^ inStream);
public virtual void Load (System.IO.Stream inStream);
abstract member Load : System.IO.Stream -> unit
override this.Load : System.IO.Stream -> unit
Public Overridable Sub Load (inStream As Stream)

参数

inStream
Stream

包含要加载的 XML 文档的流。The stream containing the XML document to load.

例外

XML 中存在加载或分析错误。There is a load or parse error in the XML. 在这种情况下,将引发 FileNotFoundExceptionIn this case, a FileNotFoundException is raised.

注解

备注

Load 方法始终保留有效的空白区域。The Load method always preserves significant white space. PreserveWhitespace 属性确定是否保留无关紧要的空白,即元素内容中的空格。The PreserveWhitespace property determines whether or not insignificant white space, that is white space in element content, is preserved. 默认值为 false;不保留元素内容中的空格。The default is false; white space in element content is not preserved.

如果要进行验证,可以使用 XmlReaderSettings 类和 Create 方法创建验证 XmlReader 实例。If you want validation to occur, you can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. 有关详细信息,请参阅 XmlReader 引用页的“备注”部分。For more information, see the Remarks section of the XmlReader reference page.

此方法是文档对象模型(DOM)的 Microsoft 扩展。This method is a Microsoft extension to the Document Object Model (DOM).

此方法自动检测输入 XML 的字符串格式(例如,UTF-8、ANSI,等等)。This method automatically detects the string format of the input XML (for example, UTF-8, ANSI, and so on). 如果你的应用程序需要知道使用哪种编码来读取流,请考虑使用 XmlTextReader 对象读取流,然后使用 XmlTextReader.Encoding 属性来确定编码。If your application needs to know which encoding is used to read the stream, consider using an XmlTextReader object to read the stream, and then use the XmlTextReader.Encoding property to determine the encoding. 如果需要使用 XmlDocument 对象处理 XML,可以使用 XmlTextReader 对象创建一个。If you need to use a XmlDocument object to work with XML, you can use the XmlTextReader object to create one. 有关详细信息,请参阅使用 XPathDocument 和 Xml 读取 XML 数据For more information, see Reading XML Data using XPathDocument and XmlDocument.

另请参阅

Load(TextReader)

从指定的 TextReader 加载 XML 文档。Loads the XML document from the specified TextReader.

public:
 virtual void Load(System::IO::TextReader ^ txtReader);
public virtual void Load (System.IO.TextReader txtReader);
abstract member Load : System.IO.TextReader -> unit
override this.Load : System.IO.TextReader -> unit
Public Overridable Sub Load (txtReader As TextReader)

参数

txtReader
TextReader

用于将 XML 数据输送到文档中的 TextReaderThe TextReader used to feed the XML data into the document.

例外

XML 中存在加载或分析错误。There is a load or parse error in the XML. 在这种情况下,该文档保留为空。In this case, the document remains empty.

示例

下面的示例使用 StringReader 类将 XML 数据的字符串加载到 XmlDocument 对象中。The following example uses the StringReader class to load a string of XML data into the XmlDocument object.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   // Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   String^ xmlData = "<book xmlns:bk='urn:samples'></book>";
   doc->Load( gcnew StringReader( xmlData ) );
   
   // Create a new element and add it to the document.
   XmlElement^ elem = doc->CreateElement( "bk", "genre", "urn:samples" );
   elem->InnerText = "fantasy";
   doc->DocumentElement->AppendChild( elem );
   Console::WriteLine( "Display the modified XML..." );
   doc->Save( Console::Out );
}

using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    string xmlData = "<book xmlns:bk='urn:samples'></book>";

    doc.Load(new StringReader(xmlData));

    // Create a new element and add it to the document.
    XmlElement elem = doc.CreateElement("bk", "genre", "urn:samples");
    elem.InnerText = "fantasy";
    doc.DocumentElement.AppendChild(elem);

    Console.WriteLine("Display the modified XML...");
    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()
    Dim xmlData as string = "<book xmlns:bk='urn:samples'></book>"

    doc.Load(new StringReader(xmlData))

    ' Create a new element and add it to the document.
    Dim elem as XmlElement = doc.CreateElement("bk", "genre", "urn:samples")
    elem.InnerText = "fantasy"
    doc.DocumentElement.AppendChild(elem)

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

  end sub
end class

注解

备注

Load 方法始终保留有效的空白区域。The Load method always preserves significant white space. PreserveWhitespace 属性确定是否保留无关紧要的空白,即元素内容中的空格。The PreserveWhitespace property determines whether or not insignificant white space, that is white space in element content, is preserved. 默认值为 false;不保留元素内容中的空格。The default is false; white space in element content is not preserved.

如果要进行验证,可以使用 XmlReaderSettings 类和 Create 方法创建验证 XmlReader 实例。If you want validation to occur, you can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. 有关详细信息,请参阅 XmlReader 引用页的“备注”部分。For more information, see the Remarks section of the XmlReader reference page.

此方法是文档对象模型(DOM)的 Microsoft 扩展。This method is a Microsoft extension to the Document Object Model (DOM).

另请参阅

Load(String)

从指定的 URL 加载 XML 文档。Loads the XML document from the specified URL.

public:
 virtual void Load(System::String ^ filename);
public virtual void Load (string filename);
abstract member Load : string -> unit
override this.Load : string -> unit
Public Overridable Sub Load (filename As String)

参数

filename
String

含要加载的 XML 文档的文件的 URL。URL for the file containing the XML document to load. URL 既可以是本地文件,也可以是 HTTP URL(Web 地址)。The URL can be either a local file or an HTTP URL (a Web address).

例外

XML 中存在加载或分析错误。There is a load or parse error in the XML. 在这种情况下,将引发 FileNotFoundExceptionIn this case, a FileNotFoundException is raised.

filename 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。filename is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

filenamenullfilename is null.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

指定的路径无效(例如,它位于未映射的驱动器上)。The specified path is invalid (for example, it is on an unmapped drive).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

filename 指定了一个只读文件。filename specified a file that is read-only.

- 或 --or- 当前平台不支持此操作。This operation is not supported on the current platform.

- 或 --or- filename 指定了一个目录。filename specified a directory.

- 或 --or- 调用方没有所要求的权限。The caller does not have the required permission.

未找到 filename 中指定的文件。The file specified in filename was not found.

filename 的格式无效。filename is in an invalid format.

调用方没有所要求的权限。The caller does not have the required permission.

注解

备注

Load 方法始终保留有效的空白区域。The Load method always preserves significant white space. PreserveWhitespace 属性确定是否保留无关紧要的空白,即元素内容中的空格。The PreserveWhitespace property determines whether or not insignificant white space, that is white space in element content, is preserved. 默认值为 false;不保留元素内容中的空格。The default is false; white space in element content is not preserved.

如果要进行验证,可以使用 XmlReaderSettings 类和 Create 方法创建验证 XmlReader 实例。If you want validation to occur, you can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. 有关详细信息,请参阅 XmlReader 引用页的“备注”部分。For more information, see the Remarks section of the XmlReader reference page.

此方法是文档对象模型(DOM)的 Microsoft 扩展。This method is a Microsoft extension to the Document Object Model (DOM).

另请参阅

Load(XmlReader)

从指定的 XmlReader 加载 XML 文档。Loads the XML document from the specified XmlReader.

public:
 virtual void Load(System::Xml::XmlReader ^ reader);
public virtual void Load (System.Xml.XmlReader reader);
abstract member Load : System.Xml.XmlReader -> unit
override this.Load : System.Xml.XmlReader -> unit
Public Overridable Sub Load (reader As XmlReader)

参数

reader
XmlReader

用于将 XML 数据输送到文档中的 XmlReaderThe XmlReader used to feed the XML data into the document.

例外

XML 中存在加载或分析错误。There is a load or parse error in the XML. 在这种情况下,该文档保留为空。In this case, the document remains empty.

示例

下面的示例将 books.xml 文件的最后一个 book 节点加载到 XML 文档中。The following example loads the last book node of the books.xml file into the XML document.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   
   //Load the document with the last book node.
   XmlTextReader^ reader = gcnew XmlTextReader( "books.xml" );
   reader->WhitespaceHandling = WhitespaceHandling::None;
   reader->MoveToContent();
   reader->Read();
   reader->Skip(); //Skip the first book.
   reader->Skip(); //Skip the second book.
   doc->Load( reader );
   doc->Save( Console::Out );
}

using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();

    //Load the document with the last book node.
    XmlTextReader reader = new XmlTextReader("books.xml");
    reader.WhitespaceHandling = WhitespaceHandling.None;
    reader.MoveToContent();
    reader.Read();
    reader.Skip(); //Skip the first book.
    reader.Skip(); //Skip the second book.
    doc.Load(reader);

    doc.Save(Console.Out);
  }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        
        'Load the document with the last book node.
        Dim reader As New XmlTextReader("books.xml")
        reader.WhitespaceHandling = WhitespaceHandling.None
        reader.MoveToContent()
        reader.Read()
        reader.Skip() 'Skip the first book.
        reader.Skip() 'Skip the second book.
        doc.Load(reader)
        
        doc.Save(Console.Out)
    End Sub
End Class

该示例使用文件(books.xml)作为输入。The example uses the file, books.xml, as input.

<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

注解

备注

Load 方法始终保留有效的空白区域。The Load method always preserves significant white space. PreserveWhitespace 属性确定是否保留无关紧要的空白,即元素内容中的空格。The PreserveWhitespace property determines whether or not insignificant white space, that is white space in element content, is preserved. 默认值为 false;不保留元素内容中的空格。The default is false; white space in element content is not preserved.

如果读取器处于初始状态(ReadState = ReadState),Load 将使用读取器的全部内容,并根据所找到的内容生成 DOM。If the reader is in the initial state (ReadState =ReadState.Initial), Load consumes the entire contents of the reader and builds the DOM from what it finds.

如果读取器已位于深度为 "n" 的某个节点上,则此方法会将该节点及其所有后续同级加载到结束标记(关闭深度 "n")。If the reader is already positioned on some node at depth "n", this method loads that node and all subsequent siblings up to the end tag that closes depth "n". 这会产生以下结果。This has the following results.

如果当前节点及其同级的外观如下所示:If the current node and its siblings look like the following:

<!--comment--><element1>one</element1><element2>two</element2>  

Load 引发异常,因为文档不能有两个根级别元素。Load throws an exception because a document cannot have two root level elements. 如果当前节点及其同级的外观如下所示:If the current node and its siblings look like the following:

<!--comment--><?process instruction?><!--comment--></endtag>  

Load 成功,但你有一个不完整的 DOM 树,因为没有根级别元素。Load succeeds, but you have an incomplete DOM tree because there is no root level element. 在保存文档之前,必须添加根级别元素,否则 Save 会引发异常。Before you save the document, you must add a root level element, otherwise Save will throw an exception.

如果读取器定位在对文档根级别无效的叶节点上(例如,空白或属性节点),则读取器将继续读取,直到将其定位到可用于根的节点上。If the reader is positioned on a leaf node that is invalid for the root level of a document, for example a white space or attribute node, the reader continues to read until it is positioned on a node that can be used for the root. 文档在此时开始加载。The document begins loading at this point.

如果要进行验证,可以使用 XmlReaderSettings 类和 Create 方法创建验证 XmlReader 实例。If you want validation to occur, you can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. 有关详细信息,请参阅 XmlReader 引用页的“备注”部分。For more information, see the Remarks section of the XmlReader reference page.

此方法是文档对象模型(DOM)的 Microsoft 扩展。This method is a Microsoft extension to the Document Object Model (DOM).

另请参阅

适用于