XmlDocument XmlDocument XmlDocument XmlDocument Class

Definición

Representa un documento XML.Represents an XML document. Puede usar esta clase para cargar, validar, editar, agregar y posicionar el código XML en un documento.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
Herencia
XmlDocumentXmlDocumentXmlDocumentXmlDocument
Derivado

Comentarios

La XmlDocument clase es una representación en memoria de un documento XML.The XmlDocument class is an in-memory representation of an XML document. Implementa el nivel 1 del W3C XML Document Object Model (dom) y el nivel 2 del DOM principal.It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2.

Dom significa el modelo de objetos de documento.DOM stands for document object model. Para obtener más información al respecto, consulte Document Object Model XML (dom).To read more about it, see XML Document Object Model (DOM).

Puede cargar XML en Dom mediante la XmlDocument clase y, a continuación, leer, modificar y quitar XML en el documento mediante programación.You can load XML into the DOM by using the XmlDocument class, and then programmatically read, modify, and remove XML in the document.

Si desea abrir la XmlDocument clase y ver cómo se implementa, vea el origen de referencia.If you want to pry open the XmlDocument class and see how it's implemented, see the Reference Source.

TareasTasks

Cargar XML en el modelo de objetos de documentoLoad XML into the document object model

Comience con un documento XML como este que tenga algunos libros en una colección.Start with an XML document like this one that has a few books in a collection. Contiene los elementos básicos que se encontraban en cualquier documento XML, incluido un espacio de nombres, elementos que representan datos y atributos que describen los datos.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>  

A continuación, cargue estos datos en el DOM para poder trabajar con ellos en la memoria.Next, load this data into the DOM so that you can work with it in memory. La forma más habitual de hacerlo es hacer referencia a un archivo en el equipo local o en una red.The most popular way to do this is refer to a file on your local computer or on a network.

En este ejemplo se carga XML desde un archivo.This example loads XML from a file. Si el archivo no existe, simplemente genera código XML y lo carga.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

Ejemplo completo: Manipular XML en memoria mediante la clase XmlDocument y otros tipos relacionadosComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Más información: Lectura de un documento XML en DOMLearn more: Reading an XML Document into the DOM

Validarlo con respecto a un esquemaValidate it against a schema

Comience con un esquema XML como este.Start with an XML schema like this one. Este esquema define los tipos de datos en el XML y los atributos que son necesarios.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>  

Cree un XmlReader objeto con el esquema y, a continuación, cargue ese objeto en el Dom.Create an XmlReader object by using your schema, and then load that object into the DOM. Cree un controlador de eventos que se ejecute cuando el código intente modificar el archivo XML de maneras que infrinjan las reglas del esquema.Create an event handler that executes when code attempts to modify your XML file in ways that violate the rules of the schema.

Estos bloques de código muestran métodos auxiliares que hacen todo esto.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

Ejemplo completo: Manipular XML en memoria mediante la clase XmlDocument y otros tipos relacionadosComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Más información: Validación de un documento XML en DOMLearn more: Validating an XML Document in the DOM

Puede utilizar las propiedades para desplazarse por un documento XML.You can use properties to navigate around an XML document. Pero antes de usar cualquiera de ellos, vamos a revisar rápidamente algunos términos.But before you use any of them, let's quickly review a few terms. El documento se compone de nodos.Your document is composed of nodes. Cada nodo tiene un único nodo primario directamente por encima de él.Each node has as single parent node directly above it. El único nodo que no tiene un nodo primario es la raíz del documento, ya que es el nodo de nivel superior.The only node that does not have a parent node is the document root, as it is the top-level node. La mayoría de los nodos pueden tener nodos secundarios , que son nodos directamente debajo de ellos.Most nodes can have child nodes, which are nodes directly below them. Los nodos que están en el mismo nivel son hermanos.Nodes that are at the same level are siblings.

En los siguientes ejemplos se muestra cómo obtener el nodo raíz, saltar al primer nodo secundario del nodo raíz, obtener acceso a cualquiera de sus nodos secundarios, volver al nodo primario y, a continuación, navegar por los nodos del mismo nivel.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.

Inicio con el nodo raízStart with the root node

En este ejemplo se obtiene el nodo raíz y, a continuación, se usa ese nodo para generar el contenido del documento en la consola.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

Obtener nodos secundariosGet child nodes

En este ejemplo se salta al primer nodo secundario del nodo raíz y, a continuación, se recorre en iteración los nodos secundarios de ese nodo, si existe alguno.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

Volver al nodo primarioGet back to the parent node

Utilice la propiedad ParentNode.Use the ParentNode property.

Hacer referencia al último nodo secundarioRefer to the last child node

En este ejemplo se escribe el precio de un libro en la consola.This example writes the price of a book to the console. El nodo de precio es el último elemento secundario de un nodo de libro.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

Navegar hacia delante en elementos del mismo nivelNavigate forward across siblings

En este ejemplo se avanza del libro al libro.This example moves forward from book to book. Los nodos de libro son hermanos entre sí.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

Navegar hacia atrás por los elementos del mismo nivelNavigate backwards across siblings

Este ejemplo se desplaza hacia atrás desde el libro al libro.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

Buscar nodosFind nodes

La forma más popular de encontrar uno o varios nodos de datos es usar una cadena de consulta XPath, pero también hay métodos que no requieren uno.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.

Obtener un solo nodoGet a single node

En este ejemplo se busca un libro mediante el número 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

La cadena usada en este ejemplo es una consulta XPath.The string used in this example is an Xpath query. Puede encontrar más ejemplos aquí: Ejemplos de XPath.You can find more examples of them here: XPath examples.

También puede utilizar GetElementById para recuperar nodos.You can also use the GetElementById to retrieve nodes. Para usar este enfoque, tendrá que definir el identificador en las declaraciones de definición de tipo de documento del archivo XML.To use this approach, you'll have to define ID's in the document type definition declarations of your XML file.

Después de obtener un nodo, obtiene el valor de los atributos o nodos secundarios.After you get a node, you get the value of attributes or child nodes. Este ejemplo lo hace con un nodo de libro.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

Obtener una colección de nodosGet a collection of nodes

En este ejemplo se seleccionan todos los libros en los que el apellido del autor es Austeny, a continuación, se cambia el precio de dichos libros.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

También puede obtener una colección de nodos mediante el nombre del nodo.You can also get a collection of nodes by using the name of the node. Por ejemplo, en este ejemplo se obtiene una colección de todos los títulos de libros.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

Ejemplo completo: Manipular XML en memoria mediante la clase XmlDocument y otros tipos relacionadosComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Más información: Selección de nodos con la navegación XPathLearn more: Select Nodes Using XPath Navigation

Editar nodosEdit nodes

En este ejemplo se edita un nodo de libro y sus atributos.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

Más información: Modificación de nodos, contenido y valores en un documento XMLLearn more: Modifying Nodes, Content, and Values in an XML Document

Ejemplo completo: Manipular XML en memoria mediante la clase XmlDocument y otros tipos relacionadosComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Agregar nodosAdd nodes

Para agregar un nodo, use el CreateElement método o el CreateNode método.To add a node, use the CreateElement method or the CreateNode method.

Para agregar un nodo de datos, como un libro, use CreateElement el método.To add a data node such as a book, use the CreateElement method.

Para cualquier otro tipo de nodo, como un comentario, un nodo de espacio en blanco o un nodo CreateNode CDATA, use el método.For any other type of node such as a comment, whitespace node, or CDATA node, use the CreateNode method.

En este ejemplo se crea un nodo de libro, se agregan atributos a ese nodo y, a continuación, se agrega ese nodo al documento.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

Ejemplo completo: Manipular XML en memoria mediante la clase XmlDocument y otros tipos relacionadosComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Más información: Inserción de nodos en un documento XMLLearn more: Inserting Nodes into an XML Document

Quitar nodosRemove nodes

Para quitar un nodo, use el RemoveChild método.To remove a node, use the RemoveChild method.

En este ejemplo se quita un libro del documento y los espacios en blanco que aparecen justo antes del nodo de libro.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

Ejemplo completo: Manipular XML en memoria mediante la clase XmlDocument y otros tipos relacionadosComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Más información: Eliminación de nodos, contenido y valores de un documento XMLLearn more: Removing Nodes, Content, and Values from an XML Document

Colocar nodosPosition nodes

Puede elegir dónde desea que aparezca un nodo en el documento mediante los InsertBefore métodos y. InsertAfterYou can choose where you want a node to appear in your document by using the InsertBefore and InsertAfter methods.

En este ejemplo se muestran dos métodos auxiliares.This example shows two helper methods. Uno de ellos mueve un nodo hacia arriba en una lista.One of them moves a node higher in a list. El otro mueve un nodo hacia abajo.The other one moves a node lower.

Estos métodos se pueden utilizar en una aplicación que permite a los usuarios subir y bajar los libros en una lista de libros.These methods could be used in an application that enables users to move books up and down in a list of books. Cuando un usuario elige un libro y presiona un botón arriba o abajo, el código podría llamar a métodos como estos para colocar el nodo de libro correspondiente antes o después de otros nodos de libro.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

Ejemplo completo: Manipular XML en memoria mediante la clase XmlDocument y otros tipos relacionadosComplete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Constructores

XmlDocument() XmlDocument() XmlDocument() XmlDocument()

Inicializa una nueva instancia de la clase XmlDocument.Initializes a new instance of the XmlDocument class.

XmlDocument(XmlImplementation) XmlDocument(XmlImplementation) XmlDocument(XmlImplementation) XmlDocument(XmlImplementation)

Inicializa una nueva instancia de la clase XmlDocument con el objeto XmlImplementation especificado.Initializes a new instance of the XmlDocument class with the specified XmlImplementation.

XmlDocument(XmlNameTable) XmlDocument(XmlNameTable) XmlDocument(XmlNameTable) XmlDocument(XmlNameTable)

Inicializa una nueva instancia de la clase XmlDocument con el objeto XmlNameTable especificado.Initializes a new instance of the XmlDocument class with the specified XmlNameTable.

Propiedades

Attributes Attributes Attributes Attributes

Obtiene un objeto XmlAttributeCollection que contiene los atributos de este nodo.Gets an XmlAttributeCollection containing the attributes of this node.

(Inherited from XmlNode)
BaseURI BaseURI BaseURI BaseURI

Obtiene el identificador URI base del nodo actual.Gets the base URI of the current node.

ChildNodes ChildNodes ChildNodes ChildNodes

Obtiene todos los nodos secundarios del nodo.Gets all the child nodes of the node.

(Inherited from XmlNode)
DocumentElement DocumentElement DocumentElement DocumentElement

Obtiene el XmlElement raíz del documento.Gets the root XmlElement for the document.

DocumentType DocumentType DocumentType DocumentType

Obtiene el nodo que contiene la declaración DOCTYPE.Gets the node containing the DOCTYPE declaration.

FirstChild FirstChild FirstChild FirstChild

Obtiene el primer nodo secundario del nodo.Gets the first child of the node.

(Inherited from XmlNode)
HasChildNodes HasChildNodes HasChildNodes HasChildNodes

Obtiene un valor que indica si este nodo tiene nodos secundarios.Gets a value indicating whether this node has any child nodes.

(Inherited from XmlNode)
Implementation Implementation Implementation Implementation

Obtiene el objeto XmlImplementation del documento actual.Gets the XmlImplementation object for the current document.

InnerText InnerText InnerText InnerText

Produce una InvalidOperationException en todos los casos.Throws an InvalidOperationException in all cases.

InnerXml InnerXml InnerXml InnerXml

Obtiene o establece el marcado que representa los nodos secundarios del nodo actual.Gets or sets the markup representing the children of the current node.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

Obtiene un valor que indica si el nodo actual es de solo lectura.Gets a value indicating whether the current node is read-only.

Item[String, String] Item[String, String] Item[String, String] Item[String, String]

Obtiene el primer elemento secundario con el LocalName y el NamespaceURI especificados.Gets the first child element with the specified LocalName and NamespaceURI.

(Inherited from XmlNode)
Item[String] Item[String] Item[String] Item[String]

Obtiene el primer elemento secundario con el Name especificado.Gets the first child element with the specified Name.

(Inherited from XmlNode)
LastChild LastChild LastChild LastChild

Obtiene el último nodo secundario del nodo.Gets the last child of the node.

(Inherited from XmlNode)
LocalName LocalName LocalName LocalName

Obtiene el nombre local del nodo.Gets the local name of the node.

Name Name Name Name

Obtiene el nombre completo del nodo.Gets the qualified name of the node.

NamespaceURI NamespaceURI NamespaceURI NamespaceURI

Obtiene el identificador URI de espacio de nombres de este nodo.Gets the namespace URI of this node.

(Inherited from XmlNode)
NameTable NameTable NameTable NameTable

Obtiene el XmlNameTable asociado a esta implementación.Gets the XmlNameTable associated with this implementation.

NextSibling NextSibling NextSibling NextSibling

Obtiene el nodo inmediatamente siguiente a éste.Gets the node immediately following this node.

(Inherited from XmlNode)
NodeType NodeType NodeType NodeType

Obtiene el tipo del nodo actual.Gets the type of the current node.

OuterXml OuterXml OuterXml OuterXml

Obtiene el marcado que contiene este nodo y todos sus nodos secundarios.Gets the markup containing this node and all its child nodes.

(Inherited from XmlNode)
OwnerDocument OwnerDocument OwnerDocument OwnerDocument

Obtiene el XmlDocument al que pertenece el nodo actual.Gets the XmlDocument to which the current node belongs.

ParentNode ParentNode ParentNode ParentNode

Obtiene el nodo primario de este nodo, en los nodos que pueden tener nodos primarios.Gets the parent node of this node (for nodes that can have parents).

Prefix Prefix Prefix Prefix

Obtiene o establece el prefijo de espacio de nombres de este nodo.Gets or sets the namespace prefix of this node.

(Inherited from XmlNode)
PreserveWhitespace PreserveWhitespace PreserveWhitespace PreserveWhitespace

Obtiene o establece un valor que indica si se va a conservar el espacio en blanco del contenido del elemento.Gets or sets a value indicating whether to preserve white space in element content.

PreviousSibling PreviousSibling PreviousSibling PreviousSibling

Obtiene el nodo inmediatamente anterior a éste.Gets the node immediately preceding this node.

(Inherited from XmlNode)
PreviousText PreviousText PreviousText PreviousText

Obtiene el nodo de texto inmediatamente anterior a este.Gets the text node that immediately precedes this node.

(Inherited from XmlNode)
SchemaInfo SchemaInfo SchemaInfo SchemaInfo

Devuelve el conjunto de información posterior a la validación del esquema (PSVI, Post-Schema-Validation-Infoset) del nodo.Returns the Post-Schema-Validation-Infoset (PSVI) of the node.

Schemas Schemas Schemas Schemas

Obtiene o establece el objeto XmlSchemaSet asociado a este objeto XmlDocument.Gets or sets the XmlSchemaSet object associated with this XmlDocument.

Value Value Value Value

Obtiene o establece el valor del nodo.Gets or sets the value of the node.

(Inherited from XmlNode)
XmlResolver XmlResolver XmlResolver XmlResolver

Establece el objeto XmlResolver para usarlo en la resolución de recursos externos.Sets the XmlResolver to use for resolving external resources.

Métodos

AppendChild(XmlNode) AppendChild(XmlNode) AppendChild(XmlNode) AppendChild(XmlNode)

Agrega el nodo especificado al final de la lista de nodos secundarios de este nodo.Adds the specified node to the end of the list of child nodes, of this node.

(Inherited from XmlNode)
Clone() Clone() Clone() Clone()

Crea un duplicado de este nodo.Creates a duplicate of this node.

(Inherited from XmlNode)
CloneNode(Boolean) CloneNode(Boolean) CloneNode(Boolean) CloneNode(Boolean)

Crea un duplicado de este nodo.Creates a duplicate of this node.

CreateAttribute(String) CreateAttribute(String) CreateAttribute(String) CreateAttribute(String)

Crea un objeto XmlAttribute con el Name especificado.Creates an XmlAttribute with the specified Name.

CreateAttribute(String, String) CreateAttribute(String, String) CreateAttribute(String, String) CreateAttribute(String, String)

Crea un XmlAttribute con el nombre completo especificados y el NamespaceURI.Creates an XmlAttribute with the specified qualified name and NamespaceURI.

CreateAttribute(String, String, String) CreateAttribute(String, String, String) CreateAttribute(String, String, String) CreateAttribute(String, String, String)

Crea un XmlAttribute con los Prefix, LocalName y NamespaceURI especificados.Creates an XmlAttribute with the specified Prefix, LocalName, and NamespaceURI.

CreateCDataSection(String) CreateCDataSection(String) CreateCDataSection(String) CreateCDataSection(String)

Crea un XmlCDataSection que contiene los datos especificados.Creates an XmlCDataSection containing the specified data.

CreateComment(String) CreateComment(String) CreateComment(String) CreateComment(String)

Crea un XmlComment que contiene los datos especificados.Creates an XmlComment containing the specified data.

CreateDefaultAttribute(String, String, String) CreateDefaultAttribute(String, String, String) CreateDefaultAttribute(String, String, String) CreateDefaultAttribute(String, String, String)

Crea un atributo predeterminado con el prefijo, el nombre local y el identificador URI de espacio de nombres especificados.Creates a default attribute with the specified prefix, local name and namespace URI.

CreateDocumentFragment() CreateDocumentFragment() CreateDocumentFragment() CreateDocumentFragment()

Crea una interfaz XmlDocumentFragment.Creates an XmlDocumentFragment.

CreateDocumentType(String, String, String, String) CreateDocumentType(String, String, String, String) CreateDocumentType(String, String, String, String) CreateDocumentType(String, String, String, String)

Devuelve un nuevo objeto XmlDocumentType.Returns a new XmlDocumentType object.

CreateElement(String) CreateElement(String) CreateElement(String) CreateElement(String)

Crea un elemento con el nombre especificado.Creates an element with the specified name.

CreateElement(String, String) CreateElement(String, String) CreateElement(String, String) CreateElement(String, String)

Crea un XmlElement con el nombre completo y el NamespaceURI.Creates an XmlElement with the qualified name and NamespaceURI.

CreateElement(String, String, String) CreateElement(String, String, String) CreateElement(String, String, String) CreateElement(String, String, String)

Crea un elemento con los Prefix, LocalName y NamespaceURI especificados.Creates an element with the specified Prefix, LocalName, and NamespaceURI.

CreateEntityReference(String) CreateEntityReference(String) CreateEntityReference(String) CreateEntityReference(String)

Crea un objeto XmlEntityReference con el nombre especificado.Creates an XmlEntityReference with the specified name.

CreateNavigator() CreateNavigator() CreateNavigator() CreateNavigator()

Crea un nuevo objeto XPathNavigator para navegar por este documento.Creates a new XPathNavigator object for navigating this document.

CreateNavigator(XmlNode) CreateNavigator(XmlNode) CreateNavigator(XmlNode) CreateNavigator(XmlNode)

Crea un objeto XPathNavigator para navegar por este documento colocado en XmlNode especificado.Creates an XPathNavigator object for navigating this document positioned on the XmlNode specified.

CreateNode(String, String, String) CreateNode(String, String, String) CreateNode(String, String, String) CreateNode(String, String, String)

Crea un XmlNode con el tipo de nodo especificado, Name y NamespaceURI.Creates an XmlNode with the specified node type, Name, and NamespaceURI.

CreateNode(XmlNodeType, String, String) CreateNode(XmlNodeType, String, String) CreateNode(XmlNodeType, String, String) CreateNode(XmlNodeType, String, String)

Crea un XmlNode con los XmlNodeType, Name y NamespaceURI especificados.Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.

CreateNode(XmlNodeType, String, String, String) CreateNode(XmlNodeType, String, String, String) CreateNode(XmlNodeType, String, String, String) CreateNode(XmlNodeType, String, String, String)

Crea un XmlNode con los XmlNodeType, Prefix, Name y NamespaceURI especificados.Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.

CreateProcessingInstruction(String, String) CreateProcessingInstruction(String, String) CreateProcessingInstruction(String, String) CreateProcessingInstruction(String, String)

Crea un XmlProcessingInstruction con el nombre y los datos especificados.Creates an XmlProcessingInstruction with the specified name and data.

CreateSignificantWhitespace(String) CreateSignificantWhitespace(String) CreateSignificantWhitespace(String) CreateSignificantWhitespace(String)

Crea un nodo XmlSignificantWhitespace.Creates an XmlSignificantWhitespace node.

CreateTextNode(String) CreateTextNode(String) CreateTextNode(String) CreateTextNode(String)

Crea un objeto XmlTextcon el texto especificado.Creates an XmlText with the specified text.

CreateWhitespace(String) CreateWhitespace(String) CreateWhitespace(String) CreateWhitespace(String)

Crea un nodo XmlWhitespace.Creates an XmlWhitespace node.

CreateXmlDeclaration(String, String, String) CreateXmlDeclaration(String, String, String) CreateXmlDeclaration(String, String, String) CreateXmlDeclaration(String, String, String)

Crea un nodo XmlDeclaration con los valores especificados.Creates an XmlDeclaration node with the specified values.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetElementById(String) GetElementById(String) GetElementById(String) GetElementById(String)

Obtiene el XmlElement con el identificador especificado.Gets the XmlElement with the specified ID.

GetElementsByTagName(String) GetElementsByTagName(String) GetElementsByTagName(String) GetElementsByTagName(String)

Devuelve un objeto XmlNodeList que contiene una lista de todos los elementos descendientes que coinciden con el Name especificado.Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.

GetElementsByTagName(String, String) GetElementsByTagName(String, String) GetElementsByTagName(String, String) GetElementsByTagName(String, String)

Devuelve un objeto XmlNodeList que contiene una lista de todos los elementos descendientes que coinciden con el LocalName y NamespaceURI especificados.Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Obtiene un enumerador que recorre en iteración los nodos secundarios del nodo actual.Gets an enumerator that iterates through the child nodes in the current node.

(Inherited from XmlNode)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetNamespaceOfPrefix(String) GetNamespaceOfPrefix(String) GetNamespaceOfPrefix(String) GetNamespaceOfPrefix(String)

Busca la declaración xmlns más cercana para el prefijo especificado que está en el ámbito del nodo actual y devuelve el identificador URI de espacio de nombres de la declaración.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.

(Inherited from XmlNode)
GetPrefixOfNamespace(String) GetPrefixOfNamespace(String) GetPrefixOfNamespace(String) GetPrefixOfNamespace(String)

Busca la declaración xmlns más cercana para el identificador URI de espacio de nombres especificado que está en el ámbito del nodo actual y devuelve el prefijo definido en la declaración.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.

(Inherited from XmlNode)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
ImportNode(XmlNode, Boolean) ImportNode(XmlNode, Boolean) ImportNode(XmlNode, Boolean) ImportNode(XmlNode, Boolean)

Importa un nodo de otro documento al documento actual.Imports a node from another document to the current document.

InsertAfter(XmlNode, XmlNode) InsertAfter(XmlNode, XmlNode) InsertAfter(XmlNode, XmlNode) InsertAfter(XmlNode, XmlNode)

Inserta el nodo especificado inmediatamente detrás del nodo de referencia igualmente especificado.Inserts the specified node immediately after the specified reference node.

(Inherited from XmlNode)
InsertBefore(XmlNode, XmlNode) InsertBefore(XmlNode, XmlNode) InsertBefore(XmlNode, XmlNode) InsertBefore(XmlNode, XmlNode)

Inserta el nodo especificado inmediatamente antes del nodo de referencia igualmente especificado.Inserts the specified node immediately before the specified reference node.

(Inherited from XmlNode)
Load(Stream) Load(Stream) Load(Stream) Load(Stream)

Carga el documento XML desde el flujo especificado.Loads the XML document from the specified stream.

Load(String) Load(String) Load(String) Load(String)

Carga el documento XML desde la dirección URL especificada.Loads the XML document from the specified URL.

Load(TextReader) Load(TextReader) Load(TextReader) Load(TextReader)

Carga el documento XML desde el TextReader especificado.Loads the XML document from the specified TextReader.

Load(XmlReader) Load(XmlReader) Load(XmlReader) Load(XmlReader)

Carga el documento XML desde el XmlReader especificado.Loads the XML document from the specified XmlReader.

LoadXml(String) LoadXml(String) LoadXml(String) LoadXml(String)

Carga el documento XML desde la cadena especificada.Loads the XML document from the specified string.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
Normalize() Normalize() Normalize() Normalize()

Hace que todos los nodos XmlText de toda la profundidad del subárbol situado bajo XmlNode aparezcan de forma "normal", de modo que solo el marcado (es decir, las etiquetas, comentarios, instrucciones de procesamiento, secciones CDATA y referencias a entidades) separa los nodos XmlText, es decir, no hay nodos XmlText adyacentes.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.

(Inherited from XmlNode)
PrependChild(XmlNode) PrependChild(XmlNode) PrependChild(XmlNode) PrependChild(XmlNode)

Agrega el nodo especificado al principio de la lista de nodos secundarios de este nodo.Adds the specified node to the beginning of the list of child nodes for this node.

(Inherited from XmlNode)
ReadNode(XmlReader) ReadNode(XmlReader) ReadNode(XmlReader) ReadNode(XmlReader)

Crea un objeto XmlNode tomando como base la información de XmlReader.Creates an XmlNode object based on the information in the XmlReader. El lector debe estar situado en un nodo o en un atributo.The reader must be positioned on a node or attribute.

RemoveAll() RemoveAll() RemoveAll() RemoveAll()

Quita todos los atributos y nodos secundarios del nodo actual.Removes all the child nodes and/or attributes of the current node.

(Inherited from XmlNode)
RemoveChild(XmlNode) RemoveChild(XmlNode) RemoveChild(XmlNode) RemoveChild(XmlNode)

Quita el nodo secundario especificado.Removes specified child node.

(Inherited from XmlNode)
ReplaceChild(XmlNode, XmlNode) ReplaceChild(XmlNode, XmlNode) ReplaceChild(XmlNode, XmlNode) ReplaceChild(XmlNode, XmlNode)

Reemplaza el nodo secundario oldChild por el nodo newChild.Replaces the child node oldChild with newChild node.

(Inherited from XmlNode)
Save(Stream) Save(Stream) Save(Stream) Save(Stream)

Guarda el documento XML en el flujo especificado.Saves the XML document to the specified stream.

Save(String) Save(String) Save(String) Save(String)

Guarda el documento XML en el archivo especificado.Saves the XML document to the specified file. Si existe el archivo especificado, este método lo sobrescribe.If the specified file exists, this method overwrites it.

Save(TextWriter) Save(TextWriter) Save(TextWriter) Save(TextWriter)

Guarda el documento XML en el TextWriter especificado.Saves the XML document to the specified TextWriter.

Save(XmlWriter) Save(XmlWriter) Save(XmlWriter) Save(XmlWriter)

Guarda el documento XML en el XmlWriter especificado.Saves the XML document to the specified XmlWriter.

SelectNodes(String) SelectNodes(String) SelectNodes(String) SelectNodes(String)

Selecciona una lista de nodos que coinciden con la expresión XPath.Selects a list of nodes matching the XPath expression.

(Inherited from XmlNode)
SelectNodes(String, XmlNamespaceManager) SelectNodes(String, XmlNamespaceManager) SelectNodes(String, XmlNamespaceManager) SelectNodes(String, XmlNamespaceManager)

Selecciona una lista de nodos que coinciden con la expresión XPath.Selects a list of nodes matching the XPath expression. Los prefijos encontrados en la expresión XPath se resuelven utilizando el XmlNamespaceManager proporcionado.Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager.

(Inherited from XmlNode)
SelectSingleNode(String) SelectSingleNode(String) SelectSingleNode(String) SelectSingleNode(String)

Selecciona el primer XmlNode que coincide con la expresión XPath.Selects the first XmlNode that matches the XPath expression.

(Inherited from XmlNode)
SelectSingleNode(String, XmlNamespaceManager) SelectSingleNode(String, XmlNamespaceManager) SelectSingleNode(String, XmlNamespaceManager) SelectSingleNode(String, XmlNamespaceManager)

Selecciona el primer XmlNode que coincide con la expresión XPath.Selects the first XmlNode that matches the XPath expression. Los prefijos encontrados en la expresión XPath se resuelven utilizando el XmlNamespaceManager proporcionado.Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager.

(Inherited from XmlNode)
Supports(String, String) Supports(String, String) Supports(String, String) Supports(String, String)

Comprueba si la implementación de DOM incluye una característica específica.Tests if the DOM implementation implements a specific feature.

(Inherited from XmlNode)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
Validate(ValidationEventHandler) Validate(ValidationEventHandler) Validate(ValidationEventHandler) Validate(ValidationEventHandler)

Valida el objeto XmlDocument según los esquemas del lenguaje de definición de esquemas XML (XSD) de la propiedad Schemas.Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.

Validate(ValidationEventHandler, XmlNode) Validate(ValidationEventHandler, XmlNode) Validate(ValidationEventHandler, XmlNode) Validate(ValidationEventHandler, XmlNode)

Valida el objeto XmlNode especificado según los esquemas del lenguaje de definición de esquemas XML (XSD) de la propiedad Schemas.Validates the XmlNode object specified against the XML Schema Definition Language (XSD) schemas in the Schemas property.

WriteContentTo(XmlWriter) WriteContentTo(XmlWriter) WriteContentTo(XmlWriter) WriteContentTo(XmlWriter)

Guarda todos los nodos secundarios del nodo XmlDocument en el XmlWriter especificado.Saves all the children of the XmlDocument node to the specified XmlWriter.

WriteTo(XmlWriter) WriteTo(XmlWriter) WriteTo(XmlWriter) WriteTo(XmlWriter)

Guarda el nodo XmlDocument en el XmlWriter especificado.Saves the XmlDocument node to the specified XmlWriter.

Eventos

NodeChanged NodeChanged NodeChanged NodeChanged

Se produce cuando el Value de un nodo que pertenece a este documento se modifica.Occurs when the Value of a node belonging to this document has been changed.

NodeChanging NodeChanging NodeChanging NodeChanging

Se produce cuando el Value de un nodo que pertenece a este documento se va a modificar.Occurs when the Value of a node belonging to this document is about to be changed.

NodeInserted NodeInserted NodeInserted NodeInserted

Se produce cuando un nodo que pertenece a este documento se ha insertado en otro nodo.Occurs when a node belonging to this document has been inserted into another node.

NodeInserting NodeInserting NodeInserting NodeInserting

Se produce cuando un nodo que pertenece a este documento se va a insertar en otro nodo.Occurs when a node belonging to this document is about to be inserted into another node.

NodeRemoved NodeRemoved NodeRemoved NodeRemoved

Se produce cuando un nodo que pertenece a este documento se ha quitado de su nodo primario.Occurs when a node belonging to this document has been removed from its parent.

NodeRemoving NodeRemoving NodeRemoving NodeRemoving

Se produce cuando un nodo que pertenece a este documento se va a quitar del documento.Occurs when a node belonging to this document is about to be removed from the document.

Implementaciones de interfaz explícitas

ICloneable.Clone() ICloneable.Clone() ICloneable.Clone() ICloneable.Clone()

Para una descripción de este miembro, vea Clone().For a description of this member, see Clone().

(Inherited from XmlNode)
IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

Para obtener una descripción de este miembro, vea GetEnumerator().For a description of this member, see GetEnumerator().

(Inherited from XmlNode)

Métodos de extensión

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

Filtra los elementos de IEnumerable en función de un tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Habilita la paralelización de una consulta.Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable.

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

Se aplica a

Consulte también: