XmlDocument 类

定义

表示 XML 文档。 可以使用此类在文档中加载、验证、编辑、添加和定位 XML。

public ref class XmlDocument : System::Xml::XmlNode
public class XmlDocument : System.Xml.XmlNode
type XmlDocument = class
    inherit XmlNode
Public Class XmlDocument
Inherits XmlNode
继承
XmlDocument
派生

注解

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 文件的文档类型定义声明中定义 ID。

获取节点后,将获取属性或子节点的值。 本例使用书籍节点执行此操作。

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 文档中删除节点、内容和值

放置节点

可以使用InsertBeforeInsertAfter方法来选择节点在文档中显示的位置。

此示例显示了两个帮助程序方法。 其中一个将节点在列表中向上移动。 另一种用于在列表中向下移动节点。

这些方法可以在应用程序中使用,使用户可以在书籍列表中上下移动书籍。 当用户选择书籍并按向上或向下按钮时,代码可以调用此类方法来定位其他书籍节点之前或之后对应的书籍节点。

//************************************************************************************
//
//  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

构造函数

名称 说明
XmlDocument()

初始化 XmlDocument 类的新实例。

XmlDocument(XmlImplementation)

用指定的XmlDocument值初始化类的新实例XmlImplementation

XmlDocument(XmlNameTable)

用指定的XmlDocument值初始化类的新实例XmlNameTable

属性

名称 说明
Attributes

获取包含 XmlAttributeCollection 此节点的属性。

(继承自 XmlNode)
BaseURI

获取当前节点的基 URI。

ChildNodes

获取节点的所有子节点。

(继承自 XmlNode)
DocumentElement

获取文档的根 XmlElement

DocumentType

获取包含 DOCTYPE 声明的节点。

FirstChild

获取节点的第一个子级。

(继承自 XmlNode)
HasChildNodes

获取一个值,该值指示此节点是否具有任何子节点。

(继承自 XmlNode)
Implementation

XmlImplementation获取当前文档的对象。

InnerText

在所有情况下都引发一个 InvalidOperationException

InnerText

获取或设置节点及其所有子节点的串联值。

(继承自 XmlNode)
InnerXml

获取或设置表示当前节点的子级的标记。

IsReadOnly

获取一个值,该值指示当前节点是否为只读节点。

Item[String, String]

获取具有指定 LocalNameNamespaceURI. 的第一个子元素。

(继承自 XmlNode)
Item[String]

获取具有指定 Name项的第一个子元素。

(继承自 XmlNode)
LastChild

获取节点的最后一个子级。

(继承自 XmlNode)
LocalName

获取节点的本地名称。

Name

获取节点的限定名称。

NamespaceURI

获取此节点的命名空间 URI。

(继承自 XmlNode)
NameTable

获取 XmlNameTable 与此实现关联的值。

NextSibling

获取紧跟此节点的节点。

(继承自 XmlNode)
NodeType

获取当前节点的类型。

OuterXml

获取包含此节点及其所有子节点的标记。

(继承自 XmlNode)
OwnerDocument

XmlDocument获取当前节点所属的节点。

ParentNode

获取此节点的父节点(对于可以具有父节点的节点)。

ParentNode

获取此节点的父级(对于可以具有父节点的节点)。

(继承自 XmlNode)
Prefix

获取或设置此节点的命名空间前缀。

(继承自 XmlNode)
PreserveWhitespace

获取或设置一个值,该值指示是否在元素内容中保留空格。

PreviousSibling

获取紧邻此节点的节点。

(继承自 XmlNode)
PreviousText

获取紧邻此节点前面的文本节点。

(继承自 XmlNode)
SchemaInfo

返回节点的架构后Validation-Infoset(PSVI)。

Schemas

获取或设置 XmlSchemaSet 与此 XmlDocument关联的对象。

Value

获取或设置节点的值。

(继承自 XmlNode)
XmlResolver

XmlResolver设置用于解析外部资源。

方法

名称 说明
AppendChild(XmlNode)

将指定的节点添加到此节点的子节点列表的末尾。

(继承自 XmlNode)
Clone()

创建此节点的重复项。

(继承自 XmlNode)
CloneNode(Boolean)

创建此节点的重复项。

CreateAttribute(String, String, String)

XmlAttribute使用指定的PrefixLocalNameNamespaceURI

CreateAttribute(String, String)

XmlAttribute创建具有指定限定名和 NamespaceURI.

CreateAttribute(String)

使用指定的XmlAttribute值创建一个 Name

CreateCDataSection(String)

创建一个 XmlCDataSection 包含指定数据的数据。

CreateComment(String)

创建一个 XmlComment 包含指定数据的数据。

CreateDefaultAttribute(String, String, String)

创建具有指定前缀、本地名称和命名空间 URI 的默认属性。

CreateDocumentFragment()

创建 XmlDocumentFragment

CreateDocumentType(String, String, String, String)

返回一个新 XmlDocumentType 对象。

CreateElement(String, String, String)

创建具有指定PrefixLocalNameNamespaceURI.

CreateElement(String, String)

创建一个 XmlElement 具有限定名和 NamespaceURI.

CreateElement(String)

创建具有指定名称的元素。

CreateEntityReference(String)

使用指定名称创建一个 XmlEntityReference

CreateNavigator()

创建用于导航此文档的新 XPathNavigator 对象。

CreateNavigator()

创建用于导航此对象的对象 XPathNavigator

(继承自 XmlNode)
CreateNavigator(XmlNode)

创建一个 XPathNavigator 对象,用于在指定位置 XmlNode 导航此文档。

CreateNode(String, String, String)

使用指定的节点类型创建一个 XmlNodeName以及 NamespaceURI

CreateNode(XmlNodeType, String, String, String)

XmlNode使用指定的 XmlNodeTypePrefixNameNamespaceURI

CreateNode(XmlNodeType, String, String)

XmlNode使用指定的XmlNodeTypeNameNamespaceURI

CreateProcessingInstruction(String, String)

使用指定的名称和数据创建一个 XmlProcessingInstruction

CreateSignificantWhitespace(String)

创建节点 XmlSignificantWhitespace

CreateTextNode(String)

使用指定的文本创建一个 XmlText

CreateWhitespace(String)

创建节点 XmlWhitespace

CreateXmlDeclaration(String, String, String)

XmlDeclaration创建具有指定值的节点。

Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
GetElementById(String)

获取 XmlElement 具有指定 ID 的 ID。

GetElementsByTagName(String, String)

返回一个 XmlNodeList 包含与指定 LocalNameNamespaceURI匹配的所有子代元素的列表。

GetElementsByTagName(String)

返回一个 XmlNodeList 包含与指定 Name匹配的所有子代元素的列表。

GetEnumerator()

获取循环访问当前节点中的子节点的枚举器。

(继承自 XmlNode)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetNamespaceOfPrefix(String)

查找当前节点范围内给定前缀的最接近 的 xmlns 声明,并在声明中返回命名空间 URI。

(继承自 XmlNode)
GetPrefixOfNamespace(String)

查找位于当前节点范围内给定命名空间 URI 的最接近 的 xmlns 声明,并返回该声明中定义的前缀。

(继承自 XmlNode)
GetType()

获取当前实例的 Type

(继承自 Object)
ImportNode(XmlNode, Boolean)

将节点从另一个文档导入到当前文档。

InsertAfter(XmlNode, XmlNode)

在指定的引用节点之后立即插入指定的节点。

(继承自 XmlNode)
InsertBefore(XmlNode, XmlNode)

在指定的引用节点之前立即插入指定的节点。

(继承自 XmlNode)
Load(Stream)

从指定的流加载 XML 文档。

Load(String)

从指定的 URL 加载 XML 文档。

Load(TextReader)

从指定的 TextReader..

Load(XmlReader)

从指定的 XmlReader..

LoadXml(String)

从指定的字符串加载 XML 文档。

MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
Normalize()

将所有 XmlText 节点置于此 XmlNode 下子树的全深度,形成“普通”形式,其中只有标记(即标记、注释、处理指令、CDATA 节和实体引用)分隔 XmlText 节点,也就是说,没有相邻的 XmlText 节点。

(继承自 XmlNode)
PrependChild(XmlNode)

将指定的节点添加到此节点的子节点列表的开头。

(继承自 XmlNode)
ReadNode(XmlReader)

基于 .. XmlNode中的信息创建对象XmlReader。 读取器必须定位在节点或属性上。

RemoveAll()

删除当前节点的所有子节点和/或属性。

(继承自 XmlNode)
RemoveChild(XmlNode)

删除指定的子节点。

(继承自 XmlNode)
ReplaceChild(XmlNode, XmlNode)

将子节点 oldChild 替换为 newChild 节点。

(继承自 XmlNode)
Save(Stream)

将 XML 文档保存到指定的流。

Save(String)

将 XML 文档保存到指定文件。 如果指定的文件存在,此方法将覆盖它。

Save(TextWriter)

将 XML 文档保存到指定的 TextWriter

Save(XmlWriter)

将 XML 文档保存到指定的 XmlWriter

SelectNodes(String, XmlNamespaceManager)

选择与 XPath 表达式匹配的节点列表。 使用提供 XmlNamespaceManager的任何前缀解析 XPath 表达式中找到的任何前缀。

(继承自 XmlNode)
SelectNodes(String)

选择与 XPath 表达式匹配的节点列表。

(继承自 XmlNode)
SelectSingleNode(String, XmlNamespaceManager)

选择与 XPath 表达式匹配的第一个 XmlNode 。 使用提供 XmlNamespaceManager的任何前缀解析 XPath 表达式中找到的任何前缀。

(继承自 XmlNode)
SelectSingleNode(String)

选择与 XPath 表达式匹配的第一个 XmlNode

(继承自 XmlNode)
Supports(String, String)

测试 DOM 实现是否实现特定功能。

(继承自 XmlNode)
ToString()

返回一个表示当前对象的字符串。

(继承自 Object)
Validate(ValidationEventHandler, XmlNode)

XmlNode验证针对属性中的 Schemas XML 架构定义语言 (XSD) 架构指定的对象。

Validate(ValidationEventHandler)

XmlDocument验证属性中包含的 Schemas XML 架构定义语言 (XSD) 架构。

WriteContentTo(XmlWriter)

将节点的所有子级 XmlDocument 保存到指定的 XmlWriter

WriteTo(XmlWriter)

XmlDocument 节点保存到指定的 XmlWriter

活动

名称 说明
NodeChanged

当属于此文档的 Value 节点已更改时发生。

NodeChanging

当属于此文档的节点即将更改时 Value 发生。

NodeInserted

当属于此文档的节点已插入到另一个节点时发生。

NodeInserting

当属于此文档的节点即将插入到另一个节点时发生。

NodeRemoved

从其父级中删除属于此文档的节点时发生。

NodeRemoving

当属于此文档的节点即将从文档中删除时发生。

显式接口实现

名称 说明
ICloneable.Clone()

有关此成员的说明,请参阅 Clone()

(继承自 XmlNode)
IEnumerable.GetEnumerator()

有关此成员的说明,请参阅 GetEnumerator()

(继承自 XmlNode)

扩展方法

名称 说明
AsParallel(IEnumerable)

启用查询的并行化。

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryable

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定类型。

CreateNavigator(XmlDocument, XmlNode)

创建一个 XPath 导航器对象,用于导航位于指定节点上的指定文档。

CreateNavigator(XmlDocument)

创建用于导航指定文档的新 XPath 导航器对象。

CreateNavigator(XmlNode)

创建用于导航指定节点的 XPath 导航器。

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。

SelectNodes(XmlNode, String, XmlNamespaceManager)

选择与指定的 XPath 表达式匹配的节点列表。 使用提供的命名空间管理器解析 XPath 表达式中找到的任何前缀。

SelectNodes(XmlNode, String)

选择与指定的 XPath 表达式匹配的节点列表。

SelectSingleNode(XmlNode, String, XmlNamespaceManager)

选择与 XPath 表达式匹配的第一个节点。 使用提供的命名空间管理器解析 XPath 表达式中找到的任何前缀。

SelectSingleNode(XmlNode, String)

选择与 XPath 表达式匹配的第一个节点。

ToXPathNavigable(XmlNode)

IXPathNavigable创建用于生成导航器的实例。

适用于

另请参阅