XmlDocument Clase

Definición

Representa un documento XML. Puede usar esta clase para cargar, validar, editar, agregar y colocar XML en un documento.

public ref class XmlDocument : System::Xml::XmlNode
public class XmlDocument : System.Xml.XmlNode
type XmlDocument = class
    inherit XmlNode
Public Class XmlDocument
Inherits XmlNode
Herencia
XmlDocument
Derivado

Comentarios

La XmlDocument clase es una representación en memoria de un documento XML. Implementa el núcleo del modelo de objetos de documento XML (DOM) W3C y el nivel 2 del DOM principal.

DOM significa modelo de objetos de documento. Para obtener más información, consulte Xml Document Object Model (DOM) (Modelo de objetos de documento XML [DOM]).

Puede cargar XML en el DOM mediante la XmlDocument clase y, a continuación, leer, modificar y quitar XML en el documento mediante programación.

Si desea abrir la XmlDocument clase y ver cómo se implementa, consulte el origen de referencia.

Cargar XML en el modelo de objetos de documento

Comience con un documento XML como este que tenga algunos libros en una colección. Contiene los elementos básicos que encontraría en cualquier documento XML, incluidos un espacio de nombres, elementos que representan datos y atributos que describen los datos.

<?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 que pueda trabajar con ellos en la memoria. La forma más popular de hacerlo es hacer referencia a un archivo en el equipo local o en una red.

En este ejemplo se carga XML desde un archivo. Si el archivo no existe, solo genera algunos XML y lo carga.

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

Para obtener más información, vea Leer un documento XML en el DOM.

Validarlo con un esquema

Comience con un esquema XML como este. Este esquema define los tipos de datos en el XML y qué atributos son necesarios.

<?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 mediante el esquema y, a continuación, cargue ese objeto en el 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.

Estos bloques de código muestran métodos auxiliares que hacen todo esto.

//************************************************************************************
//
//  Helper method that generates an XML string.
//
//************************************************************************************
private string generateXMLString()
{
    string xml = "<?xml version=\"1.0\"?> \n" +
        "<books xmlns=\"http://www.contoso.com/books\"> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
        "    <title>Pride And Prejudice</title> \n" +
        "    <price>24.95</price> \n" +
        "  </book> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
        "    <title>The Handmaid's Tale</title> \n" +
        "    <price>29.95</price> \n" +
        "  </book> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861001-45-3\" publicationdate=\"1811-01-01\"> \n" +
        "    <title>Sense and Sensibility</title> \n" +
        "    <price>19.95</price> \n" +
        "  </book> \n" +
        "</books>";
    return xml;
}

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************
public XmlDocument LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader reader = null;
    XmlReaderSettings settings = new XmlReaderSettings();
    // Helper method to retrieve schema.
    XmlSchema schema = getSchema(generateSchema);

    settings.Schemas.Add(schema);
    settings.ValidationEventHandler += ValidationCallback;
    settings.ValidationFlags =
        settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationType = ValidationType.Schema;
    if (!generateXML)
    {
        try
        {
            reader = XmlReader.Create("booksData.xml", settings);
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine(
                $"XML file not found so generating: {ex.Message}");
            generateXML = true;
        }
    }

    if (generateXML)
    {
        string xml = generateXMLString();
        StringReader stringReader = new StringReader(xml);

        reader = XmlReader.Create(stringReader, settings);
    }

    XmlDocument doc = new XmlDocument();

    doc.PreserveWhitespace = true;
    doc.Load(reader);
    reader.Close();

    return doc;
}

//************************************************************************************
//
//  Helper method that generates an XML Schema.
//
//************************************************************************************
private string generateXMLSchema()
{
    string xmlSchema =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
        "<xs:schema attributeFormDefault=\"unqualified\" " +
        "elementFormDefault=\"qualified\" targetNamespace=\"http://www.contoso.com/books\" " +
        "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"> " +
        "<xs:element name=\"books\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element maxOccurs=\"unbounded\" name=\"book\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element name=\"title\" type=\"xs:string\" /> " +
        "<xs:element name=\"price\" type=\"xs:decimal\" /> " +
        "</xs:sequence> " +
        "<xs:attribute name=\"genre\" type=\"xs:string\" use=\"required\" /> " +
        "<xs:attribute name=\"publicationdate\" type=\"xs:date\" use=\"required\" /> " +
        "<xs:attribute name=\"ISBN\" type=\"xs:string\" use=\"required\" /> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:sequence> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:schema> ";
    return xmlSchema;
}

//************************************************************************************
//
//  Helper method that gets a schema
//
//************************************************************************************
private XmlSchema getSchema(bool generateSchema)
{
    XmlSchemaSet xs = new XmlSchemaSet();
    XmlSchema schema = null;

    if (!generateSchema)
    {
        try
        {
            schema = xs.Add("http://www.contoso.com/books", "booksData.xsd");
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine(
                $"XSD file not found so generating: {ex.Message}");
            generateSchema = true;
        }
    }

    if (generateSchema)
    {
        string xmlSchemaString = generateXMLSchema();
        StringReader stringReader = new StringReader(xmlSchemaString);
        XmlReader reader = XmlReader.Create(stringReader);

        schema = xs.Add("http://www.contoso.com/books", reader);
    }

    return schema;
}

//************************************************************************************
//
//  Helper method to validate the XML against the schema.
//
//************************************************************************************
private void validateXML(bool generateSchema, XmlDocument doc)
{
    if (doc.Schemas.Count == 0)
    {
        // Helper method to retrieve schema.
        XmlSchema schema = getSchema(generateSchema);
        doc.Schemas.Add(schema);
    }

    // Use a callback to validate the XML node against the schema.
    doc.Validate(ValidationCallback);
}

//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************
void ValidationCallback(object sender,
    System.Xml.Schema.ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {
        Console.WriteLine
            ("The following validation warning occurred: " + e.Message);
    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        Console.WriteLine
            ("The following critical validation errors occurred: " + e.Message);
    }
}
'************************************************************************************
'
'  Associate the schema with XML. Then, load the XML and validate it against
'  the schema.
'
'************************************************************************************
Public Function LoadDocumentWithSchemaValidation(ByVal generateXML As Boolean, ByVal generateSchema As Boolean) As XmlDocument
    Dim reader As XmlReader
    Dim settings As XmlReaderSettings = New XmlReaderSettings
    ' Helper method to retrieve schema.
    Dim schema As XmlSchema = getSchema(generateSchema)
    If (schema Is Nothing) Then
        Return Nothing
    End If
    settings.Schemas.Add(schema)
    AddHandler settings.ValidationEventHandler, AddressOf settings_ValidationEventHandler
    settings.ValidationFlags = (settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings)
    settings.ValidationType = ValidationType.Schema
    Try
        reader = XmlReader.Create("booksData.xml", settings)
    Catch ex As System.IO.FileNotFoundException
        If generateXML Then
            Dim xml As String = generateXMLString()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xml)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            reader = XmlReader.Create(stream, settings)
        Else
            Return Nothing
        End If
    End Try
    Dim doc As XmlDocument = New XmlDocument
    doc.PreserveWhitespace = True
    doc.Load(reader)
    reader.Close()
    Return doc
End Function

'************************************************************************************
'
'  Helper method that generates an XML Schema.
'
'************************************************************************************
Private Function generateXMLSchema() As String

    Dim generatedXmlSchema As String = "<?xml version=""1.0"" encoding=""utf-8""?> " & _
            "<xs:schema attributeFormDefault=""unqualified"" " & _
            "elementFormDefault=""qualified"" targetNamespace=""http://www.contoso.com/books"" " & _
            "xmlns:xs=""http://www.w3.org/2001/XMLSchema""> " & _
            "<xs:element name=""books""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element maxOccurs=""unbounded"" name=""book""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element name=""title"" type=""xs:string"" /> " & _
            "<xs:element name=""price"" type=""xs:decimal"" /> " & _
            "</xs:sequence> " & _
            "<xs:attribute name=""genre"" type=""xs:string"" use=""required"" /> " & _
            "<xs:attribute name=""publicationdate"" type=""xs:date"" use=""required"" /> " & _
            "<xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" /> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:sequence> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:schema> "


    Return generatedXmlSchema

End Function

'************************************************************************************
'
'  Helper method that gets a schema
'
'************************************************************************************
Private Function getSchema(ByVal generateSchema As Boolean) As XmlSchema
    Dim xs As XmlSchemaSet = New XmlSchemaSet
    Dim schema As XmlSchema
    Try
        schema = xs.Add("http://www.contoso.com/books", "booksData.xsd")
    Catch ex As System.IO.FileNotFoundException
        If generateSchema Then
            Dim xmlSchemaString As String = generateXMLSchema()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xmlSchemaString)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            Dim reader As XmlReader = XmlReader.Create(stream)
            schema = xs.Add("http://www.contoso.com/books", reader)
        Else
            Return Nothing
        End If
    End Try
    Return schema
End Function

'************************************************************************************
'
'  Helper method to validate the XML against the schema.
'
'************************************************************************************
Private Sub validateXML(ByVal generateSchema As Boolean, ByVal doc As XmlDocument)
    If (doc.Schemas.Count = 0) Then
        ' Helper method to retrieve schema.
        Dim schema As XmlSchema = getSchema(generateSchema)
        doc.Schemas.Add(schema)
    End If
    ' Use an event handler to validate the XML node against the schema.
    doc.Validate(AddressOf settings_ValidationEventHandler)
End Sub

'************************************************************************************
'
'  Event handler that is raised when XML doesn't validate against the schema.
'
'************************************************************************************
Private Sub settings_ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)
    If (e.Severity = XmlSeverityType.Warning) Then
        System.Windows.Forms.MessageBox.Show(("The following validation warning occurred: " & e.Message))
    ElseIf (e.Severity = XmlSeverityType.Error) Then
        System.Windows.Forms.MessageBox.Show(("The following critical validation errors occurred: " & e.Message))
        Dim objectType As Type = sender.GetType
    End If
End Sub

Para obtener más información, consulte Validación de un documento XML en dom.

Puede usar propiedades para desplazarse por un documento XML. Pero antes de usar cualquiera de ellos, vamos a revisar rápidamente algunos términos. El documento se compone de nodos. Cada nodo tiene un único nodo primario directamente encima de él. El único nodo que no tiene un nodo primario es la raíz del documento, ya que es el nodo de nivel superior. La mayoría de los nodos pueden tener nodos secundarios , que son nodos directamente debajo de ellos. Los nodos que están en el mismo nivel son hermanos.

En los ejemplos siguientes se muestra cómo obtener el nodo raíz, saltar al primer nodo secundario del nodo raíz, acceder a cualquiera de sus nodos secundarios, volver al nodo primario y, a continuación, navegar por los nodos del mismo nivel.

Comience con el nodo raíz.

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.

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

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<?xml version='1.0' ?>" +
                "<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    //Display the document element.
    Console.WriteLine(doc.DocumentElement.OuterXml);
 }
}
Option Strict On
Option Explicit On
Imports System.Xml

Public Class ElementSample
    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.LoadXml("<?xml version='1.0' ?>" &
                    "<book genre='novel' ISBN='1-861001-57-5'>" &
                    "<title>Pride And Prejudice</title>" &
                    "</book>")

        'Display the document element.
        Console.WriteLine(doc.DocumentElement.OuterXml)
    End Sub
End Class

Obtención de nodos secundarios

En este ejemplo se salta al primer nodo secundario del nodo raíz y, a continuación, recorre en iteración los nodos secundarios de ese nodo si existe alguno.

using System;
using System.Xml;

public class Sample2
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "<price>19.95</price>" +
                    "</book>");

        XmlNode root = doc.FirstChild;

        //Display the contents of the child nodes.
        if (root.HasChildNodes)
        {
            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                Console.WriteLine(root.ChildNodes[i].InnerText);
            }
        }
    }
}
Option Strict
Option Explicit

Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        'Display the contents of the child nodes.
        If root.HasChildNodes Then
            Dim i As Integer
            For i = 0 To root.ChildNodes.Count - 1
                Console.WriteLine(root.ChildNodes(i).InnerText)
            Next i
        End If
    End Sub
End Class

Volver al nodo primario

Use la propiedad ParentNode.

Consulte el último nodo secundario.

En este ejemplo se escribe el precio de un libro en la consola. El nodo de precio es el último elemento secundario de un nodo de libro.

using System;
using System.Xml;

public class Sample3
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "<price>19.95</price>" +
                    "</book>");

        XmlNode root = doc.FirstChild;

        Console.WriteLine("Display the price element...");
        Console.WriteLine(root.LastChild.OuterXml);
    }
}
Option Explicit On
Option Strict On
Imports System.Xml

Public Class LastChildSample
    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" &
                    "<title>Pride And Prejudice</title>" &
                    "<price>19.95</price>" &
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        Console.WriteLine("Display the price element...")
        Console.WriteLine(root.LastChild.OuterXml)
    End Sub
End Class

Navegar hacia delante a través de elementos del mismo nivel

Este ejemplo avanza de libro a libro. Los nodos de libro son elementos del mismo nivel.

using System;
using System.Xml;

public class Sample4
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("books.xml");

        XmlNode currNode = doc.DocumentElement.FirstChild;
        Console.WriteLine("First book...");
        Console.WriteLine(currNode.OuterXml);

        XmlNode nextNode = currNode.NextSibling;
        Console.WriteLine("\r\nSecond book...");
        Console.WriteLine(nextNode.OuterXml);
    }
}
Imports System.Xml

Public Class NextSiblingSample
    Public Shared Sub Main()

        Dim doc As XmlDocument = New XmlDocument()
        doc.Load("books.xml")

        Dim currNode As XmlNode = doc.DocumentElement.FirstChild
        Console.WriteLine("First book...")
        Console.WriteLine(currNode.OuterXml)

        Dim nextNode As XmlNode = currNode.NextSibling
        Console.WriteLine(ControlChars.Lf + "Second book...")
        Console.WriteLine(nextNode.OuterXml)

    End Sub
End Class

Navegar hacia atrás entre elementos del mismo nivel

Este ejemplo retrocede de libro en libro.

using System;
using System.Xml;

public class Sample {

  public static void Main() {

      XmlDocument doc = new XmlDocument();
      doc.Load("books.xml");

      XmlNode lastNode = doc.DocumentElement.LastChild;
      Console.WriteLine("Last book...");
      Console.WriteLine(lastNode.OuterXml);

      XmlNode prevNode = lastNode.PreviousSibling;
      Console.WriteLine("\r\nPrevious book...");
      Console.WriteLine(prevNode.OuterXml);
  }
}
Imports System.Xml

Public Class Sample5
    Public Shared Sub Main()
        Dim doc As XmlDocument = New XmlDocument()
        doc.Load("books.xml")

        Dim lastNode As XmlNode = doc.DocumentElement.LastChild
        Console.WriteLine("Last book...")
        Console.WriteLine(lastNode.OuterXml)

        Dim prevNode As XmlNode = lastNode.PreviousSibling
        Console.WriteLine(ControlChars.Lf + "Previous book...")
        Console.WriteLine(prevNode.OuterXml)
    End Sub
End Class

Buscar nodos

La forma más popular de buscar uno o varios nodos de datos es usar una cadena de consulta XPath, pero también hay métodos que no requieren uno.

Obtención de un solo nodo

En este ejemplo se busca un libro mediante el número ISBN.

public XmlNode GetBook(string uniqueAttribute, XmlDocument doc)
{
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books");
    string xPathString = "//bk:books/bk:book[@ISBN='" + uniqueAttribute + "']";
    XmlNode xmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr);
   return xmlNode;
}
Public Function GetBook(ByVal uniqueAttribute As String, ByVal doc As XmlDocument) As XmlNode
    Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books")
    Dim xPathString As String = ("//bk:books/bk:book[@ISBN='" _
                & (uniqueAttribute & "']"))
    Dim xmlNode As XmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr)
    Return xmlNode
End Function

La cadena usada en este ejemplo es una consulta Xpath. Puede encontrar más ejemplos de ellos en ejemplos de XPath.

También puede usar el GetElementById para recuperar nodos. Para usar este enfoque, tendrá que definir ID en las declaraciones de definición de tipo de documento de su archivo XML.

Después de obtener un nodo, obtendrá el valor de atributos o nodos secundarios. Este ejemplo lo hace con un nodo de libro.

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 nodos

En este ejemplo se seleccionan todos los libros en los que el apellido del autor es Austen y, a continuación, cambia el precio de esos libros.

using System;
using System.Xml;

public class Sample6
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("booksort.xml");

        XmlNodeList nodeList;
        XmlNode root = doc.DocumentElement;

        nodeList = root.SelectNodes("descendant::book[author/last-name='Austen']");

        //Change the price on the books.
        foreach (XmlNode book in nodeList)
        {
            book.LastChild.InnerText = "15.95";
        }

        Console.WriteLine("Display the modified XML document....");
        doc.Save(Console.Out);
    }
}
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    'Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksort.xml")

    Dim book as XmlNode
    Dim nodeList as XmlNodeList
    Dim root as XmlNode = doc.DocumentElement

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']")

    'Change the price on the books.
    for each book in nodeList
      book.LastChild.InnerText="15.95"
    next

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

  end sub
end class

También puede obtener una colección de nodos mediante el nombre del nodo. Por ejemplo, este ejemplo obtiene una colección de todos los títulos de libro.

using System;
using System.Xml;

public class Sample1
{
    public static void Main()
    {
        //Create the XmlDocument.
        XmlDocument doc = new XmlDocument();
        doc.Load("books.xml");

        //Display all the book titles.
        XmlNodeList elemList = doc.GetElementsByTagName("title");
        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine(elemList[i].InnerXml);
        }
    }
}
Option Explicit On
Option Strict On
Imports System.Xml

Public Class TagSample

    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.Load("books.xml")

        'Display all the book titles.
        Dim elemList As XmlNodeList = doc.GetElementsByTagName("title")
        Dim i As Integer
        For i = 0 To elemList.Count - 1
            Console.WriteLine(elemList(i).InnerXml)
        Next i
    End Sub
End Class

Para obtener más información, vea Seleccionar nodos mediante la navegación XPath.

Edición de nodos

En este ejemplo se edita un nodo de libro y sus atributos.

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

Para obtener más información, vea Modificar nodos, contenido y valores en un documento XML.

Agregar nodos

Para agregar un nodo, use el CreateElement método o el CreateNode método .

Para agregar un nodo de datos como un libro, use el CreateElement método .

Para cualquier otro tipo de nodo, como un comentario, un nodo de espacio en blanco o un nodo CDATA, use el CreateNode método .

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.

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

Para obtener más información, vea Insertar nodos en un documento XML.

Quitar nodos

Para quitar un nodo, use el RemoveChild método .

En este ejemplo se quita un libro del documento y cualquier espacio en blanco que aparezca justo antes del nodo de libro.

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

Para obtener más información, vea Quitar nodos, contenido y valores de un documento XML.

Posición de nodos

Puede elegir dónde desea que un nodo aparezca en el documento mediante los InsertBefore métodos y InsertAfter .

En este ejemplo se muestran dos métodos auxiliares. Uno de ellos mueve un nodo más alto en una lista. La otra mueve un nodo más abajo.

Estos métodos se pueden usar en una aplicación que permite a los usuarios mover libros hacia arriba y hacia abajo en una lista de libros. Cuando un usuario elige un libro y presiona un botón hacia arriba o hacia 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.

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

Constructores

Nombre Description
XmlDocument()

Inicializa una nueva instancia de la clase XmlDocument.

XmlDocument(XmlImplementation)

Inicializa una nueva instancia de la XmlDocument clase con el especificado XmlImplementation.

XmlDocument(XmlNameTable)

Inicializa una nueva instancia de la XmlDocument clase con el especificado XmlNameTable.

Propiedades

Nombre Description
Attributes

Obtiene un XmlAttributeCollection objeto que contiene los atributos de este nodo.

(Heredado de XmlNode)
BaseURI

Obtiene el URI base del nodo actual.

ChildNodes

Obtiene todos los nodos secundarios del nodo.

(Heredado de XmlNode)
DocumentElement

Obtiene la raíz XmlElement del documento.

DocumentType

Obtiene el nodo que contiene la declaración DOCTYPE.

FirstChild

Obtiene el primer elemento secundario del nodo.

(Heredado de XmlNode)
HasChildNodes

Obtiene un valor que indica si este nodo tiene nodos secundarios.

(Heredado de XmlNode)
Implementation

Obtiene el XmlImplementation objeto del documento actual.

InnerText

Produce una InvalidOperationException excepción en todos los casos.

InnerText

Obtiene o establece los valores concatenados del nodo y todos sus nodos secundarios.

(Heredado de XmlNode)
InnerXml

Obtiene o establece el marcado que representa los elementos secundarios del nodo actual.

IsReadOnly

Obtiene un valor que indica si el nodo actual es de solo lectura.

Item[String, String]

Obtiene el primer elemento secundario con el especificado LocalName y NamespaceURI.

(Heredado de XmlNode)
Item[String]

Obtiene el primer elemento secundario con el especificado Name.

(Heredado de XmlNode)
LastChild

Obtiene el último elemento secundario del nodo.

(Heredado de XmlNode)
LocalName

Obtiene el nombre local del nodo.

Name

Obtiene el nombre completo del nodo.

NamespaceURI

Obtiene el URI del espacio de nombres de este nodo.

(Heredado de XmlNode)
NameTable

Obtiene el XmlNameTable asociado a esta implementación.

NextSibling

Obtiene el nodo inmediatamente después de este nodo.

(Heredado de XmlNode)
NodeType

Obtiene el tipo del nodo actual.

OuterXml

Obtiene el marcado que contiene este nodo y todos sus nodos secundarios.

(Heredado de XmlNode)
OwnerDocument

Obtiene al XmlDocument que pertenece el nodo actual.

ParentNode

Obtiene el nodo primario de este nodo (para los nodos que pueden tener elementos primarios).

ParentNode

Obtiene el elemento primario de este nodo (para los nodos que pueden tener elementos primarios).

(Heredado de XmlNode)
Prefix

Obtiene o establece el prefijo de espacio de nombres de este nodo.

(Heredado de XmlNode)
PreserveWhitespace

Obtiene o establece un valor que indica si se debe conservar el espacio en blanco en el contenido del elemento.

PreviousSibling

Obtiene el nodo inmediatamente anterior a este nodo.

(Heredado de XmlNode)
PreviousText

Obtiene el nodo de texto que precede inmediatamente a este nodo.

(Heredado de XmlNode)
SchemaInfo

Devuelve elValidation-Infoset posterior al esquema (PSVI) del nodo.

Schemas

Obtiene o establece el XmlSchemaSet objeto asociado a este XmlDocumentobjeto .

Value

Obtiene o establece el valor del nodo.

(Heredado de XmlNode)
XmlResolver

Establece el objeto XmlResolver que se va a usar para resolver recursos externos.

Métodos

Nombre Description
AppendChild(XmlNode)

Agrega el nodo especificado al final de la lista de nodos secundarios de este nodo.

(Heredado de XmlNode)
Clone()

Crea un duplicado de este nodo.

(Heredado de XmlNode)
CloneNode(Boolean)

Crea un duplicado de este nodo.

CreateAttribute(String, String, String)

Crea un XmlAttribute objeto con el especificado Prefix, LocalNamey NamespaceURI.

CreateAttribute(String, String)

Crea un XmlAttribute objeto con el nombre completo especificado y NamespaceURI.

CreateAttribute(String)

Crea un XmlAttribute objeto con el especificado Name.

CreateCDataSection(String)

Crea un objeto XmlCDataSection que contiene los datos especificados.

CreateComment(String)

Crea un objeto XmlComment que contiene los datos especificados.

CreateDefaultAttribute(String, String, String)

Crea un atributo predeterminado con el prefijo, el nombre local y el URI del espacio de nombres especificados.

CreateDocumentFragment()

Crea una interfaz XmlDocumentFragment.

CreateDocumentType(String, String, String, String)

Devuelve un nuevo XmlDocumentType objeto.

CreateElement(String, String, String)

Crea un elemento con el especificado Prefix, LocalNamey NamespaceURI.

CreateElement(String, String)

Crea un XmlElement objeto con el nombre completo y NamespaceURI.

CreateElement(String)

Crea un elemento con el nombre especificado.

CreateEntityReference(String)

Crea un XmlEntityReference objeto con el nombre especificado.

CreateNavigator()

Crea un nuevo XPathNavigator objeto para navegar por este documento.

CreateNavigator()

Crea un XPathNavigator para navegar por este objeto.

(Heredado de XmlNode)
CreateNavigator(XmlNode)

Crea un XPathNavigator objeto para navegar por este documento colocado en el XmlNode especificado.

CreateNode(String, String, String)

Crea un XmlNode objeto con el tipo de nodo especificado, Namey NamespaceURI.

CreateNode(XmlNodeType, String, String, String)

Crea un XmlNode objeto con el especificado XmlNodeType, Prefix, Namey NamespaceURI.

CreateNode(XmlNodeType, String, String)

Crea un XmlNode objeto con el especificado XmlNodeType, Namey NamespaceURI.

CreateProcessingInstruction(String, String)

Crea un XmlProcessingInstruction objeto con el nombre y los datos especificados.

CreateSignificantWhitespace(String)

Crea un XmlSignificantWhitespace nodo.

CreateTextNode(String)

Crea un XmlText objeto con el texto especificado.

CreateWhitespace(String)

Crea un XmlWhitespace nodo.

CreateXmlDeclaration(String, String, String)

Crea un XmlDeclaration nodo con los valores especificados.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetElementById(String)

Obtiene el XmlElement objeto con el identificador especificado.

GetElementsByTagName(String, String)

Devuelve un XmlNodeList objeto que contiene una lista de todos los elementos descendientes que coinciden con el especificado LocalName y NamespaceURI.

GetElementsByTagName(String)

Devuelve un XmlNodeList objeto que contiene una lista de todos los elementos descendientes que coinciden con el especificado Name.

GetEnumerator()

Obtiene un enumerador que recorre en iteración los nodos secundarios del nodo actual.

(Heredado de XmlNode)
GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
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 URI del espacio de nombres en la declaración.

(Heredado de XmlNode)
GetPrefixOfNamespace(String)

Busca la declaración xmlns más cercana para el URI de espacio de nombres especificado que está en el ámbito del nodo actual y devuelve el prefijo definido en esa declaración.

(Heredado de XmlNode)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
ImportNode(XmlNode, Boolean)

Importa un nodo de otro documento al documento actual.

InsertAfter(XmlNode, XmlNode)

Inserta el nodo especificado inmediatamente después del nodo de referencia especificado.

(Heredado de XmlNode)
InsertBefore(XmlNode, XmlNode)

Inserta el nodo especificado inmediatamente antes del nodo de referencia especificado.

(Heredado de XmlNode)
Load(Stream)

Carga el documento XML desde la secuencia especificada.

Load(String)

Carga el documento XML desde la dirección URL especificada.

Load(TextReader)

Carga el documento XML del especificado TextReader.

Load(XmlReader)

Carga el documento XML del especificado XmlReader.

LoadXml(String)

Carga el documento XML de la cadena especificada.

MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
Normalize()

Coloca todos los nodos XmlText en la profundidad completa del subárbol debajo de este XmlNode en un formulario "normal" donde solo el marcado (es decir, etiquetas, comentarios, instrucciones de procesamiento, secciones de CDATA y referencias de entidad) separa nodos XmlText, es decir, no hay nodos XmlText adyacentes.

(Heredado de XmlNode)
PrependChild(XmlNode)

Agrega el nodo especificado al principio de la lista de nodos secundarios de este nodo.

(Heredado de XmlNode)
ReadNode(XmlReader)

Crea un XmlNode objeto basado en la información de XmlReader. El lector debe colocarse en un nodo o atributo.

RemoveAll()

Quita todos los nodos secundarios o atributos del nodo actual.

(Heredado de XmlNode)
RemoveChild(XmlNode)

Quita el nodo secundario especificado.

(Heredado de XmlNode)
ReplaceChild(XmlNode, XmlNode)

Reemplaza el nodo oldChild secundario por newChild el nodo .

(Heredado de XmlNode)
Save(Stream)

Guarda el documento XML en la secuencia especificada.

Save(String)

Guarda el documento XML en el archivo especificado. Si el archivo especificado existe, este método lo sobrescribe.

Save(TextWriter)

Guarda el documento XML en el especificado TextWriter.

Save(XmlWriter)

Guarda el documento XML en el especificado XmlWriter.

SelectNodes(String, XmlNamespaceManager)

Selecciona una lista de nodos que coinciden con la expresión XPath. Los prefijos encontrados en la expresión XPath se resuelven mediante el proporcionado XmlNamespaceManager.

(Heredado de XmlNode)
SelectNodes(String)

Selecciona una lista de nodos que coinciden con la expresión XPath.

(Heredado de XmlNode)
SelectSingleNode(String, XmlNamespaceManager)

Selecciona la primera XmlNode que coincide con la expresión XPath. Los prefijos encontrados en la expresión XPath se resuelven mediante el proporcionado XmlNamespaceManager.

(Heredado de XmlNode)
SelectSingleNode(String)

Selecciona la primera XmlNode que coincide con la expresión XPath.

(Heredado de XmlNode)
Supports(String, String)

Comprueba si la implementación dom implementa una característica específica.

(Heredado de XmlNode)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
Validate(ValidationEventHandler, XmlNode)

Valida el XmlNode objeto especificado en los esquemas del lenguaje de definición de esquemas XML (XSD) de la Schemas propiedad .

Validate(ValidationEventHandler)

Valida con XmlDocument los esquemas del lenguaje de definición de esquemas XML (XSD) contenidos en la Schemas propiedad .

WriteContentTo(XmlWriter)

Guarda todos los elementos secundarios del XmlDocument nodo en el especificado XmlWriter.

WriteTo(XmlWriter)

Guarda el XmlDocument nodo en el especificado XmlWriter.

Eventos

Nombre Description
NodeChanged

Se produce cuando se ha cambiado el Value de un nodo que pertenece a este documento.

NodeChanging

Se produce cuando el Value de un nodo que pertenece a este documento está a punto de cambiarse.

NodeInserted

Se produce cuando se ha insertado un nodo que pertenece a este documento en otro nodo.

NodeInserting

Se produce cuando un nodo que pertenece a este documento está a punto de insertarse en otro nodo.

NodeRemoved

Se produce cuando se ha quitado un nodo que pertenece a este documento de su elemento primario.

NodeRemoving

Se produce cuando un nodo que pertenece a este documento está a punto de quitarse del documento.

Implementaciones de interfaz explícitas

Nombre Description
ICloneable.Clone()

Para obtener una descripción de este miembro, vea Clone().

(Heredado de XmlNode)
IEnumerable.GetEnumerator()

Para obtener una descripción de este miembro, vea GetEnumerator().

(Heredado de XmlNode)

Métodos de extensión

Nombre Description
AsParallel(IEnumerable)

Habilita la paralelización de una consulta.

AsQueryable(IEnumerable)

Convierte un IEnumerable en un IQueryable.

Cast<TResult>(IEnumerable)

Convierte los elementos de un IEnumerable al tipo especificado.

CreateNavigator(XmlDocument, XmlNode)

Crea un objeto de navegador XPath para navegar por el documento especificado situado en el nodo especificado.

CreateNavigator(XmlDocument)

Crea un nuevo objeto de navegador XPath para navegar por el documento especificado.

CreateNavigator(XmlNode)

Crea un navegador XPath para navegar por el nodo especificado.

OfType<TResult>(IEnumerable)

Filtra los elementos de un IEnumerable en función de un tipo especificado.

SelectNodes(XmlNode, String, XmlNamespaceManager)

Selecciona una lista de nodos que coinciden con la expresión XPath especificada. Los prefijos encontrados en la expresión XPath se resuelven mediante el administrador de espacios de nombres proporcionado.

SelectNodes(XmlNode, String)

Selecciona una lista de nodos que coinciden con la expresión XPath especificada.

SelectSingleNode(XmlNode, String, XmlNamespaceManager)

Selecciona el primer nodo que coincide con la expresión XPath. Los prefijos encontrados en la expresión XPath se resuelven mediante el administrador de espacios de nombres proporcionado.

SelectSingleNode(XmlNode, String)

Selecciona el primer nodo que coincide con la expresión XPath.

ToXPathNavigable(XmlNode)

Crea una IXPathNavigable instancia que se usa para generar navegadores.

Se aplica a

Consulte también