XmlDocument 类

定义

表示 XML 文档。Represents an XML document. 可使用此类在文档中加载、验证、编辑、添加和放置 XML。You can use this class to load, validate, edit, add, and position XML in a document.

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 文档的内存中表示形式。The XmlDocument class is an in-memory representation of an XML document. 它实现 W3C XML 文档对象模型 (DOM)级别1核心和核心 DOM 级别2。It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2.

DOM代表文档对象模型DOM stands for document object model. 若要了解有关详细信息, 请参阅XML 文档对象模型 (DOM)To read more about it, see XML Document Object Model (DOM).

您可以使用类将XmlDocument xml 加载到 DOM 中, 然后在文档中以编程方式读取、修改和删除 xml。You can load XML into the DOM by using the XmlDocument class, and then programmatically read, modify, and remove XML in the document.

如果要撬开XmlDocument该类并查看其实现方式, 请参阅引用源If you want to pry open the XmlDocument class and see how it's implemented, see the Reference Source.

任务Tasks

将 XML 加载到文档对象模型Load XML into the document object model

从一个 XML 文档开始, 其中包含集合中的一些书籍。Start with an XML document like this one that has a few books in a collection. 它包含您在任何 XML 文档中可以找到的基本内容, 其中包括命名空间、表示数据的元素以及用于描述数据的特性。It contains the basic things that you'd find in any XML document, including a namespace, elements that represent data, and attributes that describe the data.

<?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 中, 以便可以在内存中使用它。Next, load this data into the DOM so that you can work with it in memory. 要执行此操作, 最常见的方法是引用本地计算机或网络上的文件。The most popular way to do this is refer to a file on your local computer or on a network.

此示例从文件加载 XML。This example loads XML from a file. 如果该文件不存在, 则只生成一些 XML 并加载。If the file doesn't exist, it just generates some XML and loads that.

XmlDocument ^doc = gcnew XmlDocument();
doc->PreserveWhitespace = true;
try
{doc->Load("booksData.xml");}
catch (System::IO::FileNotFoundException ^e1)
{
    // If no book is found, generate some XML.

    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>");
}
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 类和其他相关类型在内存中操作 XMLComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:将 XML 文档读入 DOMLearn more: Reading an XML Document into the DOM

根据架构对其进行验证Validate it against a schema

从此类 XML 架构开始。Start with an XML schema like this one. 此架构定义 XML 中的数据类型以及所需的属性。This schema defines the data types in the XML and which attributes are required.

<?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>  

使用架构创建对象, 然后将该对象加载到 DOM。 XmlReaderCreate an XmlReader object by using your schema, and then load that object into the DOM. 创建一个事件处理程序, 该事件处理程序在代码尝试使用违反架构规则的方式修改 XML 文件时执行。Create an event handler that executes when code attempts to modify your XML file in ways that violate the rules of the schema.

这些代码块显示执行所有此操作的帮助器方法。These blocks of code show helper methods that do all of this.

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************

XmlDocument ^XMLDOMProcessing::XMLHelperMethods::LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader ^reader;

    XmlReaderSettings ^settings = gcnew XmlReaderSettings();

    // Helper method to retrieve schema.
    XmlSchema ^schema = getSchema(generateSchema);
    
    if (schema == nullptr)
    {
        return nullptr;
    }

    settings->Schemas->Add(schema);
    settings->ValidationEventHandler +=
        gcnew System::Xml::Schema::ValidationEventHandler
        (this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);
    settings->ValidationFlags = settings->ValidationFlags | XmlSchemaValidationFlags::ReportValidationWarnings;
    settings->ValidationType = ValidationType::Schema;

    try
    {
        reader = XmlReader::Create("booksData.xml", settings);
    }
    catch (System::IO::FileNotFoundException ^e1)
    {
        if (generateXML)
        {
            String ^xml = generateXMLString();
            array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xml);
            MemoryStream ^stream = gcnew MemoryStream(byteArray);
            reader = XmlReader::Create(stream, settings);
        }
        else
        {
            return nullptr;
        }

    }

    XmlDocument ^doc = gcnew XmlDocument();
    doc->PreserveWhitespace = true;
    doc->Load(reader);
    reader->Close();

    return doc;
}

//************************************************************************************
//
//  Helper method that generates an XML Schema.
//
//************************************************************************************

String ^XMLDOMProcessing::XMLHelperMethods::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
//
//************************************************************************************

XmlSchema ^XMLDOMProcessing::XMLHelperMethods::getSchema(bool generateSchema)
{
    XmlSchemaSet ^xs = gcnew XmlSchemaSet();
    XmlSchema ^schema;
    try
    {
        schema = xs->Add("http://www.contoso.com/books", "booksData.xsd");
    }
    catch (System::IO::FileNotFoundException ^e1)
    {
        if (generateSchema)
        {
            String ^xmlSchemaString = generateXMLSchema();
            array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xmlSchemaString);
            MemoryStream ^stream = gcnew MemoryStream(byteArray);
            XmlReader ^reader = XmlReader::Create(stream);
            schema = xs->Add("http://www.contoso.com/books", reader);
        }
        else
        {
            return nullptr;
        }

    }
    return schema;
}
//************************************************************************************
//
//  Helper method to validate the XML against the schema.
//
//************************************************************************************
bool XMLDOMProcessing::XMLHelperMethods::validateXML(bool generateSchema, XmlDocument ^doc)
{
    if (doc->Schemas->Count == 0)
    {
        // Helper method to retrieve schema.
        XmlSchema ^schema = getSchema(generateSchema);
        doc->Schemas->Add(schema);
    }

    ValidationEventHandler^ eventHandler = gcnew System::Xml::Schema::ValidationEventHandler
        (this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);

    // Use an event handler to validate the XML node against the schema.
    doc->Validate(eventHandler);

    if (_IsValid == false)
    {
        _IsValid = true;
        return false;
    }
    else
    {
        return true;
    }

}
//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************

void XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler(System::Object ^sender, System::Xml::Schema::ValidationEventArgs ^e)
{
    if (e->Severity == XmlSeverityType::Warning)
    {
        // do nothing.
    }
    else if (e->Severity == XmlSeverityType::Error)
    {
        // set some global variables.
        _IsValid = false;
        ValidationError = e->Message;
    }
}

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************
public XmlDocument LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader reader;

    XmlReaderSettings settings = new XmlReaderSettings();

    // Helper method to retrieve schema.
    XmlSchema schema = getSchema(generateSchema);

    if (schema == null)
    {
        return null;
    }

    settings.Schemas.Add(schema);

    settings.ValidationEventHandler += settings_ValidationEventHandler;
    settings.ValidationFlags =
        settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationType = ValidationType.Schema;

    try
    {
        reader = XmlReader.Create("booksData.xml", settings);
    }
    catch (System.IO.FileNotFoundException)
    {
        if (generateXML)
        {
            string xml = generateXMLString();
            byte[] byteArray = Encoding.UTF8.GetBytes(xml);
            MemoryStream stream = new MemoryStream(byteArray);
            reader = XmlReader.Create(stream, settings);
        }
        else
        {
            return null;
        }

    }

    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;
    try
    {
        schema = xs.Add("http://www.contoso.com/books", "booksData.xsd");
    }
    catch (System.IO.FileNotFoundException)
    {
        if (generateSchema)
        {
            string xmlSchemaString = generateXMLSchema();
            byte[] byteArray = Encoding.UTF8.GetBytes(xmlSchemaString);
            MemoryStream stream = new MemoryStream(byteArray);
            XmlReader reader = XmlReader.Create(stream);
            schema = xs.Add("http://www.contoso.com/books", reader);
        }
        else
        {
            return null;
        }

    }
    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 an event handler to validate the XML node against the schema.
    doc.Validate(settings_ValidationEventHandler);

}

//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************
void settings_ValidationEventHandler(object sender,
    System.Xml.Schema.ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {
        System.Windows.Forms.MessageBox.Show
            ("The following validation warning occurred: " + e.Message);
    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        System.Windows.Forms.MessageBox.Show
            ("The following critical validation errors occurred: " + e.Message);
        Type objectType = sender.GetType();
    }

}
'************************************************************************************
'
'  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

完整示例:使用 XML 类和其他相关类型在内存中操作 XMLComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:在 DOM 中验证 XML 文档Learn more: Validating an XML Document in the DOM

您可以使用属性来浏览 XML 文档。You can use properties to navigate around an XML document. 但在使用其中任何一个之前, 让我们快速回顾几个术语。But before you use any of them, let's quickly review a few terms. 文档由节点组成。Your document is composed of nodes. 每个节点在其上都有一个直接的节点。Each node has as single parent node directly above it. 唯一没有父节点的节点是文档根, 因为它是顶级节点。The only node that does not have a parent node is the document root, as it is the top-level node. 大多数节点可以有节点, 子节点直接位于其下。Most nodes can have child nodes, which are nodes directly below them. 处于相同级别的节点是同级节点。Nodes that are at the same level are siblings.

下面的示例演示如何获取根节点, 跳转到根节点的第一个子节点, 访问其任何子节点, 返回到父节点, 然后在同级节点之间导航。The following examples show you how to obtain the root node, jump to the first child node of the root node, access any of its child nodes, get back out to the parent node, and then navigate across sibling nodes.

从根节点开始Start with the root node

此示例获取根节点, 然后使用该节点将文档内容输出到控制台。This example gets the root node and then uses that node to output the contents of the document to the console.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew 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 );
}

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
Option Explicit

Imports System.IO
Imports System.Xml

Public Class Sample
    
    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

获取子节点Get child nodes

此示例跳转到根节点的第一个子节点, 然后循环访问该节点的子节点 (如果存在)。This example jumps to the first child node of the root node and then iterates through the child nodes of that node if any exist.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   XmlDocument^ doc = gcnew 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 );
      }
   }
}
using System;
using System.IO;
using System.Xml;

public class Sample {

  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

返回父节点Get back to the parent node

使用 ParentNode 属性。Use the ParentNode property.

请参阅最后一个子节点Refer to the last child node

此示例将书籍的价格写入控制台。This example writes the price of a book to the console. "价格" 节点是 book 节点的最后一个子级。The price node is the last child of a book node.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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 );
}

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

public class Sample {

  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
Option Strict

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
        
        Console.WriteLine("Display the price element...")
        Console.WriteLine(root.LastChild.OuterXml)
    End Sub
End Class

在同级之间向前导航Navigate forward across siblings

此示例将书籍中的前移。This example moves forward from book to book. Book 节点彼此同级。Book nodes are siblings to one another.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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 );
}

using System;
using System.Xml;

public class Sample {

  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 Sample 

  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

在同级之间向后导航Navigate backwards across siblings

此示例将书籍向后移动。This example moves backwards from book to book.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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 );
}

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 Sample 

  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

查找节点Find nodes

查找一个或多个数据节点的最常用方法是使用 XPath 查询字符串, 但也存在不需要的方法。The most popular way to find one or more nodes of data is to use an XPath query string, but there are also methods that don't require one.

获取单个节点Get a single node

此示例使用 ISBN 编号定位书籍。This example locates a book by using the ISBN number.

XmlNode ^XMLDOMProcessing::XMLHelperMethods::GetBook(String ^uniqueAttribute, XmlDocument ^doc)
{
    XmlNamespaceManager ^nsmgr = gcnew 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 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 查询。The string used in this example is an Xpath query. 可在此处找到更多示例: XPath 示例You can find more examples of them here: XPath examples.

你还可以使用GetElementById检索节点。You can also use the GetElementById to retrieve nodes. 若要使用此方法, 您必须在 XML 文件的文档类型定义声明中定义 ID。To use this approach, you'll have to define ID's in the document type definition declarations of your XML file.

获得节点后, 将获得属性或子节点的值。After you get a node, you get the value of attributes or child nodes. 此示例使用 book 节点执行此功能。This example does that with a book node.

void XMLDOMProcessing::XMLHelperMethods::GetBookInformation
(String ^%title, String ^%ISBN, String ^%publicationDate, String ^%price, String ^%genre, XmlNode ^book)
{
    XmlElement ^bookElement = safe_cast<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 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

获取节点的集合Get a collection of nodes

此示例选择作者姓氏为Austen的所有书籍, 然后更改这些书籍的价格。This example selects all books where the author's last name is Austen, and then changes the price of those books.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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.
   System::Collections::IEnumerator^ myEnum = nodeList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      XmlNode^ book = safe_cast<XmlNode^>(myEnum->Current);
      book->LastChild->InnerText = "15.95";
   }

   Console::WriteLine( "Display the modified XML document...." );
   doc->Save( Console::Out );
}

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

public class Sample {

  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

还可以通过使用节点的名称获取节点的集合。You can also get a collection of nodes by using the name of the node. 例如, 此示例获取所有书名的集合。For example, this example gets a collection of all book titles.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew 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 );
   }
}
using System;
using System.IO;
using System.Xml;

public class Sample
{
  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
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    
    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

完整示例:使用 XML 类和其他相关类型在内存中操作 XMLComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:使用 XPath 导航选择节点Learn more: Select Nodes Using XPath Navigation

编辑节点Edit nodes

此示例编辑书籍节点及其属性。This example edits a book node and its attributes.

bool XMLDOMProcessing::XMLHelperMethods::editBook(String ^title, String ^ISBN, String ^publicationDate, String ^genre, String ^price, XmlNode ^book, bool validateNode, bool generateSchema)
{

    XmlElement ^bookElement = safe_cast<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)
    {
        if (validateXML(generateSchema, bookElement->OwnerDocument))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    return true;
}
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 文档中的节点、内容和值Learn more: Modifying Nodes, Content, and Values in an XML Document

完整示例:使用 XML 类和其他相关类型在内存中操作 XMLComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

添加节点Add nodes

若要添加节点, 请使用CreateElement方法CreateNode或方法。To add a node, use the CreateElement method or the CreateNode method.

若要添加数据节点 (如书籍), 请使用CreateElement方法。To add a data node such as a book, use the CreateElement method.

对于任何其他类型的节点, 如注释、空白节点或 CDATA 节点, 请使用CreateNode方法。For any other type of node such as a comment, whitespace node, or CDATA node, use the CreateNode method.

此示例将创建一个 book 节点, 将属性添加到该节点, 然后将该节点添加到文档中。This example creates a book node, adds attributes to that node, and then adds that node to the document.

XmlElement ^XMLDOMProcessing::XMLHelperMethods::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 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 类和其他相关类型在内存中操作 XMLComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:将节点插入 XML 文档中Learn more: Inserting Nodes into an XML Document

删除节点Remove nodes

若要删除节点, 请使用RemoveChild方法。To remove a node, use the RemoveChild method.

此示例将从文档中删除书籍, 并删除紧靠书籍节点之前出现的任何空白。This example removes a book from the document and any whitespace that appears just before the book node.

void XMLDOMProcessing::XMLHelperMethods::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 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 类和其他相关类型在内存中操作 XMLComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

了解更多信息:从 XML 删除文档中的节点、内容和值Learn more: Removing Nodes, Content, and Values from an XML Document

位置节点Position nodes

您可以使用InsertBeforeInsertAfter方法选择要在文档中显示节点的位置。You can choose where you want a node to appear in your document by using the InsertBefore and InsertAfter methods.

此示例演示两个帮助器方法。This example shows two helper methods. 其中一项将在列表中向上移动一个节点。One of them moves a node higher in a list. 另一个节点将移动一个节点。The other one moves a node lower.

可以在应用程序中使用这些方法, 使用户能够在书籍列表中上下移动书籍。These methods could be used in an application that enables users to move books up and down in a list of books. 当用户选择一本书并按向上或向下按钮时, 您的代码就可以调用类似于这样的方法, 以便在其他书节点之前或之后定位相应的书籍节点。When a user chooses a book and presses an up or down button, your code could call methods like these to position the corresponding book node before or after other book nodes.

//************************************************************************************
//
//  Summary: Move elements up in the XML.
//  
//
//************************************************************************************
void XMLDOMProcessing::XMLHelperMethods::MoveElementUp(XmlNode ^book)
{
    XmlNode ^previousNode = book->PreviousSibling;
    while (previousNode != nullptr && (previousNode->NodeType != XmlNodeType::Element))
    {
        previousNode = previousNode->PreviousSibling;
    }
    if (previousNode != nullptr)
    {
        XmlNode ^newLineNode = book->NextSibling;
        book->OwnerDocument->DocumentElement->RemoveChild(book);
        if (newLineNode->NodeType == XmlNodeType::Whitespace || newLineNode->NodeType == XmlNodeType::SignificantWhitespace)
        {
            newLineNode->OwnerDocument->DocumentElement->RemoveChild(newLineNode);
        }
        InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionAbove, previousNode, false, false);
    }
}

//************************************************************************************
//
//  Summary: Move elements down in the XML.
//  
//
//************************************************************************************
void XMLDOMProcessing::XMLHelperMethods::MoveElementDown(XmlNode ^book)
{
    // Walk backwards until we find an element - ignore text nodes
    XmlNode ^NextNode = book->NextSibling;
    while (NextNode != nullptr && (NextNode->NodeType != XmlNodeType::Element))
    {
        NextNode = NextNode->NextSibling;
    }
    if (NextNode != nullptr)
    {
        XmlNode ^newLineNode = book->PreviousSibling;
        book->OwnerDocument->DocumentElement->RemoveChild(book);
        if (newLineNode->NodeType == XmlNodeType::Whitespace || newLineNode->NodeType == XmlNodeType::SignificantWhitespace)
        {
            newLineNode->OwnerDocument->DocumentElement->RemoveChild(newLineNode);
        }

        InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionBelow, NextNode, false, false);
    }

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

完整示例:使用 XML 类和其他相关类型在内存中操作 XMLComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

构造函数

XmlDocument()

初始化 XmlDocument 类的新实例。Initializes a new instance of the XmlDocument class.

XmlDocument(XmlImplementation)

使用指定的 XmlDocument 初始化 XmlImplementation 类的新实例。Initializes a new instance of the XmlDocument class with the specified XmlImplementation.

XmlDocument(XmlNameTable)

使用指定的 XmlDocument 初始化 XmlNameTable 类的新实例。Initializes a new instance of the XmlDocument class with the specified XmlNameTable.

属性

Attributes

获取一个 XmlAttributeCollection,它包含该节点的特性。Gets an XmlAttributeCollection containing the attributes of this node.

(继承自 XmlNode)
BaseURI

获取当前节点的基 URI。Gets the base URI of the current node.

ChildNodes

获取节点的所有子节点。Gets all the child nodes of the node.

(继承自 XmlNode)
DocumentElement

获取文档的根 XmlElementGets the root XmlElement for the document.

DocumentType

获取包含 DOCTYPE 声明的节点。Gets the node containing the DOCTYPE declaration.

FirstChild

获取节点的第一个子级。Gets the first child of the node.

(继承自 XmlNode)
HasChildNodes

获取一个值,该值指示此节点是否有任何子节点。Gets a value indicating whether this node has any child nodes.

(继承自 XmlNode)
Implementation

获取当前文档的 XmlImplementation 对象。Gets the XmlImplementation object for the current document.

InnerText

在所有情况下引发 InvalidOperationExceptionThrows an InvalidOperationException in all cases.

InnerXml

获取或设置表示当前节点的子级的标记。Gets or sets the markup representing the children of the current node.

IsReadOnly

获取一个值,该值指示当前节点是否是只读的。Gets a value indicating whether the current node is read-only.

Item[String, String]

获取具有指定 LocalNameNamespaceURI 的第一个子元素。Gets the first child element with the specified LocalName and NamespaceURI.

(继承自 XmlNode)
Item[String]

获取具有指定 Name 的第一个子元素。Gets the first child element with the specified Name.

(继承自 XmlNode)
LastChild

获取节点的最后一个子级。Gets the last child of the node.

(继承自 XmlNode)
LocalName

获取节点的本地名称。Gets the local name of the node.

Name

获取节点的限定名称。Gets the qualified name of the node.

NamespaceURI

获取该节点的命名空间 URI。Gets the namespace URI of this node.

(继承自 XmlNode)
NameTable

获取与此实现关联的 XmlNameTableGets the XmlNameTable associated with this implementation.

NextSibling

获取紧接在该节点之后的节点。Gets the node immediately following this node.

(继承自 XmlNode)
NodeType

获取当前节点的类型。Gets the type of the current node.

OuterXml

获取包含此节点及其所有子节点的标记。Gets the markup containing this node and all its child nodes.

(继承自 XmlNode)
OwnerDocument

获取当前节点所属的 XmlDocumentGets the XmlDocument to which the current node belongs.

ParentNode

获取该节点的父节点(针对可以拥有父级的节点)。Gets the parent node of this node (for nodes that can have parents).

Prefix

获取或设置该节点的命名空间前缀。Gets or sets the namespace prefix of this node.

(继承自 XmlNode)
PreserveWhitespace

获取或设置一个值,该值指示是否在元素内容中保留空白区域。Gets or sets a value indicating whether to preserve white space in element content.

PreviousSibling

获取紧接在该节点之前的节点。Gets the node immediately preceding this node.

(继承自 XmlNode)
PreviousText

获取紧接在该节点之前的文本节点。Gets the text node that immediately precedes this node.

(继承自 XmlNode)
SchemaInfo

返回节点的后架构验证信息集 (PSVI)。Returns the Post-Schema-Validation-Infoset (PSVI) of the node.

Schemas

获取或设置与此 XmlDocument 关联的 XmlSchemaSet 对象。Gets or sets the XmlSchemaSet object associated with this XmlDocument.

Value

获取或设置节点的值。Gets or sets the value of the node.

(继承自 XmlNode)
XmlResolver

设置 XmlResolver 以用于解析外部资源。Sets the XmlResolver to use for resolving external resources.

方法

AppendChild(XmlNode)

将指定的节点添加到该节点的子节点列表的末尾。Adds the specified node to the end of the list of child nodes, of this node.

(继承自 XmlNode)
Clone()

创建此节点的副本。Creates a duplicate of this node.

(继承自 XmlNode)
CloneNode(Boolean)

创建此节点的副本。Creates a duplicate of this node.

CreateAttribute(String)

创建具有指定 NameXmlAttributeCreates an XmlAttribute with the specified Name.

CreateAttribute(String, String)

创建具有指定限定名和 NamespaceURIXmlAttributeCreates an XmlAttribute with the specified qualified name and NamespaceURI.

CreateAttribute(String, String, String)

创建一个具有指定的 PrefixLocalNameNamespaceURIXmlAttributeCreates an XmlAttribute with the specified Prefix, LocalName, and NamespaceURI.

CreateCDataSection(String)

创建包含指定数据的 XmlCDataSectionCreates an XmlCDataSection containing the specified data.

CreateComment(String)

创建包含指定数据的 XmlCommentCreates an XmlComment containing the specified data.

CreateDefaultAttribute(String, String, String)

创建具有指定前缀、本地名称和命名空间 URI 的默认属性。Creates a default attribute with the specified prefix, local name and namespace URI.

CreateDocumentFragment()

创建 XmlDocumentFragmentCreates an XmlDocumentFragment.

CreateDocumentType(String, String, String, String)

返回新 XmlDocumentType 对象。Returns a new XmlDocumentType object.

CreateElement(String)

创建具有指定名称的元素。Creates an element with the specified name.

CreateElement(String, String)

创建具有限定名和 NamespaceURIXmlElementCreates an XmlElement with the qualified name and NamespaceURI.

CreateElement(String, String, String)

创建具有指定 PrefixLocalNameNamespaceURI 的元素。Creates an element with the specified Prefix, LocalName, and NamespaceURI.

CreateEntityReference(String)

创建具有指定名称的 XmlEntityReferenceCreates an XmlEntityReference with the specified name.

CreateNavigator()

创建一个用于导航此文档的新 XPathNavigator 对象。Creates a new XPathNavigator object for navigating this document.

CreateNavigator(XmlNode)

创建 XPathNavigator 对象,以定位位于指定的 XmlNode 上的此文档。Creates an XPathNavigator object for navigating this document positioned on the XmlNode specified.

CreateNode(String, String, String)

创建具有指定的节点类型、NameNamespaceURIXmlNodeCreates an XmlNode with the specified node type, Name, and NamespaceURI.

CreateNode(XmlNodeType, String, String)

创建一个具有指定的 XmlNodeTypeNameNamespaceURIXmlNodeCreates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.

CreateNode(XmlNodeType, String, String, String)

创建一个具有指定的XmlNodeTypePrefixNameNamespaceURIXmlNodeCreates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.

CreateProcessingInstruction(String, String)

创建一个具有指定名称和数据的 XmlProcessingInstructionCreates an XmlProcessingInstruction with the specified name and data.

CreateSignificantWhitespace(String)

创建一个 XmlSignificantWhitespace 节点。Creates an XmlSignificantWhitespace node.

CreateTextNode(String)

创建具有指定文本的 XmlTextCreates an XmlText with the specified text.

CreateWhitespace(String)

创建一个 XmlWhitespace 节点。Creates an XmlWhitespace node.

CreateXmlDeclaration(String, String, String)

创建一个具有指定值的 XmlDeclaration 节点。Creates an XmlDeclaration node with the specified values.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetElementById(String)

获取具有指定 ID 的 XmlElementGets the XmlElement with the specified ID.

GetElementsByTagName(String)

返回一个 XmlNodeList,它包含与指定 Name 匹配的所有子代元素的列表。Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.

GetElementsByTagName(String, String)

返回一个 XmlNodeList,它包含与指定 LocalNameNamespaceURI 匹配的所有子代元素的列表。Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.

GetEnumerator()

获取循环访问当前节点中子节点的枚举数。Gets an enumerator that iterates through the child nodes in the current node.

(继承自 XmlNode)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetNamespaceOfPrefix(String)

查找当前节点范围内离给定的前缀最近的 xmlns 声明,并返回声明中的命名空间 URI。Looks up the closest xmlns declaration for the given prefix that is in scope for the current node and returns the namespace URI in the declaration.

(继承自 XmlNode)
GetPrefixOfNamespace(String)

查找当前节点范围内离给定的命名空间 URI 最近的 xmlns 声明,并返回声明中定义的前缀。Looks up the closest xmlns declaration for the given namespace URI that is in scope for the current node and returns the prefix defined in that declaration.

(继承自 XmlNode)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

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

将节点从另一个文档导入到当前文档。Imports a node from another document to the current document.

InsertAfter(XmlNode, XmlNode)

将指定的节点紧接着插入指定的引用节点之后。Inserts the specified node immediately after the specified reference node.

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

将指定的节点紧接着插入指定的引用节点之前。Inserts the specified node immediately before the specified reference node.

(继承自 XmlNode)
Load(Stream)

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

Load(String)

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

Load(TextReader)

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

Load(XmlReader)

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

LoadXml(String)

从指定的字符串加载 XML 文档。Loads the XML document from the specified string.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Normalize()

将此 XmlNode 下子树完全深度中的所有 XmlText 节点都转换成“正常”形式,在这种形式中只有标记(即标记、注释、处理指令、CDATA 节和实体引用)分隔 XmlText 节点,也就是说,没有相邻的 XmlText 节点。Puts all XmlText nodes in the full depth of the sub-tree underneath this XmlNode into a "normal" form where only markup (that is, tags, comments, processing instructions, CDATA sections, and entity references) separates XmlText nodes, that is, there are no adjacent XmlText nodes.

(继承自 XmlNode)
PrependChild(XmlNode)

将指定的节点添加到该节点的子节点列表的开头。Adds the specified node to the beginning of the list of child nodes for this node.

(继承自 XmlNode)
ReadNode(XmlReader)

根据 XmlReader 中的信息创建一个 XmlNode 对象。Creates an XmlNode object based on the information in the XmlReader. 读取器必须定位在节点或属性上。The reader must be positioned on a node or attribute.

RemoveAll()

移除当前节点的所有子节点和/或属性。Removes all the child nodes and/or attributes of the current node.

(继承自 XmlNode)
RemoveChild(XmlNode)

移除指定的子节点。Removes specified child node.

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

oldChild 节点替换子节点 newChildReplaces the child node oldChild with newChild node.

(继承自 XmlNode)
Save(Stream)

将 XML 文档保存到指定的流。Saves the XML document to the specified stream.

Save(String)

将 XML 文档保存到指定的文件。Saves the XML document to the specified file. 如果存在指定文件,则此方法会覆盖它。If the specified file exists, this method overwrites it.

Save(TextWriter)

将 XML 文档保存到指定的 TextWriterSaves the XML document to the specified TextWriter.

Save(XmlWriter)

将 XML 文档保存到指定的 XmlWriterSaves the XML document to the specified XmlWriter.

SelectNodes(String)

选择匹配 XPath 表达式的节点列表。Selects a list of nodes matching the XPath expression.

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

选择匹配 XPath 表达式的节点列表。Selects a list of nodes matching the XPath expression. XPath 表达式中的任何前缀都使用提供的 XmlNamespaceManager 进行解析。Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager.

(继承自 XmlNode)
SelectSingleNode(String)

选择匹配 XPath 表达式的第一个 XmlNodeSelects the first XmlNode that matches the XPath expression.

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

选择匹配 XPath 表达式的第一个 XmlNodeSelects the first XmlNode that matches the XPath expression. XPath 表达式中的任何前缀都使用提供的 XmlNamespaceManager 进行解析。Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager.

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

测试 DOM 实现是否实现特定的功能。Tests if the DOM implementation implements a specific feature.

(继承自 XmlNode)
ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
Validate(ValidationEventHandler)

验证 XmlDocument 是不是 Schemas 属性中包含的 XML 架构定义语言 (XSD) 架构。Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.

Validate(ValidationEventHandler, XmlNode)

根据 Schemas 属性中的 XML 架构定义语言 (XSD) 架构,验证指定的 XmlNode 对象。Validates the XmlNode object specified against the XML Schema Definition Language (XSD) schemas in the Schemas property.

WriteContentTo(XmlWriter)

XmlDocument 节点的所有子级保存到指定的 XmlWriter 中。Saves all the children of the XmlDocument node to the specified XmlWriter.

WriteTo(XmlWriter)

XmlDocument 节点保存到指定的 XmlWriterSaves the XmlDocument node to the specified XmlWriter.

事件

NodeChanged

当属于该文档的节点的 Value 已被更改时发生。Occurs when the Value of a node belonging to this document has been changed.

NodeChanging

当属于该文档的节点的 Value 将被更改时发生。Occurs when the Value of a node belonging to this document is about to be changed.

NodeInserted

将属于该文档的节点插入另一个节点时发生。Occurs when a node belonging to this document has been inserted into another node.

NodeInserting

当属于该文档的节点将被插入另一个节点时发生。Occurs when a node belonging to this document is about to be inserted into another node.

NodeRemoved

当属于该文档的节点已从其父级中移除时发生。Occurs when a node belonging to this document has been removed from its parent.

NodeRemoving

当属于该文档的节点将从文档中移除时发生。Occurs when a node belonging to this document is about to be removed from the document.

显式界面实现

ICloneable.Clone()

有关此成员的说明,请参见 Clone()For a description of this member, see Clone().

(继承自 XmlNode)
IEnumerable.GetEnumerator()

有关此成员的说明,请参见 GetEnumerator()For a description of this member, see GetEnumerator().

(继承自 XmlNode)

扩展方法

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

CreateNavigator(XmlDocument)
CreateNavigator(XmlDocument, XmlNode)
CreateNavigator(XmlNode)
SelectNodes(XmlNode, String)
SelectNodes(XmlNode, String, XmlNamespaceManager)
SelectSingleNode(XmlNode, String)
SelectSingleNode(XmlNode, String, XmlNamespaceManager)
ToXPathNavigable(XmlNode)

适用于

另请参阅