Share via


将 XML 文档读入 DOM

XML 信息从不同的格式读入内存。 读取源包括字符串、流、URL、文本读取器或 XmlReader 的派生类。

Load 方法将文档置入内存中并包含可用于从每个不同的格式中获取数据的重载方法。 还存在 LoadXml 方法,该方法从字符串中读取 XML。

不同的 Load 方法影响在加载 XML 文档对象模型 (DOM) 时创建的节点。 下表列出了一些 Load 方法的区别以及讲述这些区别的主题。

课题

主题

创建空白节点

用来加载 DOM 的对象对 DOM 中生成的空白和有效空白节点有影响。 有关更多信息,请参见加载 DOM 时的空白和有效空白处理

从特定节点开始加载 XML 或加载整个 XML 文档

使用 XmlDocument.Load 方法可以将数据从特定的节点加载到 DOM 中。 有关更多信息,请参见从读取器中加载数据

在 XML 加载时进行验证

加载到 DOM 中的 XML 数据可以在加载时进行验证。 使用验证 XmlReader 可以完成此操作。 有关在 XML 加载时进行验证的更多信息,请参见在 DOM 中验证 XML 文档

以下示例显示使用 LoadXml 方法加载的 XML 以及之后保存到称为 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");
    }
}

请参见

概念

XML 文档对象模型 (DOM)