XmlDocument Classe

Definizione

Rappresenta un documento XML. È possibile usare questa classe per caricare, convalidare, modificare, aggiungere e posizionare xml in 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
Ereditarietà
XmlDocument
Derivato

Commenti

La XmlDocument classe è una rappresentazione in memoria di un documento XML. Implementa il Document Object Model (DOM) XML del W3C Core Livello 1 e il DOM Core Livello 2.

DOM è l'acronimo di Document Object Model. Per altre informazioni, vedere DOM (Document Object Model) XML.

È possibile caricare xml nel DOM usando la XmlDocument classe e quindi leggere, modificare e rimuovere xml a livello di codice nel documento.

Se si vuole aprire la XmlDocument classe e vedere come viene implementata, vedere l'origine di riferimento.

Caricare il codice XML nel modello a oggetti documento

Iniziare con un documento XML come questo che contiene alcuni libri in una raccolta. Contiene gli elementi di base che si trovano in qualsiasi documento XML, inclusi uno spazio dei nomi, elementi che rappresentano dati e attributi che descrivono i dati.

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

Caricare quindi questi dati nel DOM in modo che sia possibile usarli in memoria. Il modo più comune per eseguire questa operazione è fare riferimento a un file nel computer locale o in una rete.

In questo esempio viene caricato il codice XML da un file. Se il file non esiste, genera solo codice XML e lo carica.

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

Per altre informazioni, vedere Lettura di un documento XML nel DOM.

Convalidarlo rispetto a uno schema

Iniziare con uno schema XML come questo. Questo schema definisce i tipi di dati nel codice XML e gli attributi necessari.

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

Creare un XmlReader oggetto usando lo schema e quindi caricare l'oggetto nel DOM. Creare un gestore eventi che viene eseguito quando il codice tenta di modificare il file XML in modi che violano le regole dello schema.

Questi blocchi di codice mostrano metodi helper che eseguono tutto questo.

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

Per altre informazioni, vedere Convalida di un documento XML nel DOM.

È possibile utilizzare le proprietà per spostarsi in un documento XML. Ma prima di usarli, esaminiamo rapidamente alcuni termini. Il documento è costituito da nodi. Ogni nodo ha un singolo nodo padre direttamente sopra di esso. L'unico nodo che non dispone di un nodo padre è la radice del documento, perché è il nodo di primo livello. La maggior parte dei nodi può avere nodi figlio , che sono nodi direttamente sotto di essi. I nodi con lo stesso livello sono fratelli.

Gli esempi seguenti illustrano come ottenere il nodo radice, passare al primo nodo figlio del nodo radice, accedere a uno dei nodi figlio, tornare al nodo padre e quindi spostarsi tra nodi di pari livello.

Iniziare con il nodo radice

Questo esempio ottiene il nodo radice e quindi usa tale nodo per restituire il contenuto del documento nella console.

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

Ottenere nodi figli

Questo esempio passa al primo nodo figlio del nodo radice e quindi itera sui suoi nodi figlio, se presenti.

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

Tornare al nodo padre

utilizzare la proprietà ParentNode.

Fare riferimento all'ultimo nodo figlio

In questo esempio viene scritto il prezzo di un libro nella console. Il nodo prezzo è l'ultimo elemento figlio di un nodo del 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

Spostarsi in avanti tra fratelli

In questo esempio si passa da libro a libro. I nodi del libro sono di pari livello fra loro.

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

Spostarsi all'indietro tra elementi di pari livello

Questo esempio si muove all'indietro da un libro all'altro.

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

Trovare nodi

Il modo più comune per trovare uno o più nodi di dati consiste nell'usare una stringa di query XPath, ma esistono anche metodi che non ne richiedono uno.

Ottenere un singolo nodo

In questo esempio viene individuato un libro usando il numero 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 stringa usata in questo esempio è una query Xpath. Altri esempi sono disponibili negli esempi di XPath.

È anche possibile usare GetElementById per recuperare i nodi. Per usare questo approccio, è necessario definire l'ID nelle dichiarazioni di definizione del tipo di documento del file XML.

Dopo aver ottenuto un nodo, ottieni il valore degli attributi o dei nodi figlio. Questo esempio esegue questa operazione con un nodo del 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

Ottenere una raccolta di nodi

In questo esempio vengono selezionati tutti i libri in cui il cognome dell'autore è Austen e quindi viene modificato il prezzo di tali libri.

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

È anche possibile ottenere una raccolta di nodi usando il nome del nodo. Questo esempio, ad esempio, ottiene una raccolta di tutti i titoli dei libri.

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

Per ulteriori informazioni, vedere Seleziona nodi utilizzando la navigazione XPath.

Modificare i nodi

In questo esempio viene modificato un nodo di un libro e i relativi attributi.

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

Per altre informazioni, vedere Modifica di nodi, contenuto e valori in un documento XML.

Aggiungere nodi

Per aggiungere un nodo, usare il CreateElement metodo o il CreateNode metodo .

Per aggiungere un nodo dati, ad esempio un libro, usare il CreateElement metodo .

Per qualsiasi altro tipo di nodo, ad esempio un commento, un nodo spazi vuoti o un nodo CDATA, usare il CreateNode metodo .

Questo esempio crea un nodo libro, aggiunge attributi a tale nodo e quindi aggiunge tale 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

Per altre informazioni, vedere Inserimento di nodi in un documento XML.

Rimuovere i nodi

Per rimuovere un nodo, usare il RemoveChild metodo .

In questo esempio viene rimosso un libro dal documento e tutti gli spazi vuoti visualizzati poco prima del nodo 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

Per altre informazioni, vedere Rimozione di nodi, contenuto e valori da un documento XML.

Posizionare i nodi

È possibile scegliere dove visualizzare un nodo nel documento usando i InsertBefore metodi e InsertAfter .

In questo esempio vengono illustrati due metodi helper. Uno di essi sposta un nodo più in alto in un elenco. L'altro sposta un nodo in basso.

Questi metodi possono essere usati in un'applicazione che consente agli utenti di spostare i libri verso l'alto e verso il basso in un elenco di libri. Quando un utente sceglie un libro e preme un pulsante su o giù, il codice potrebbe chiamare metodi come questi per posizionare il nodo libro corrispondente prima o dopo altri nodi 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

Costruttori

Nome Descrizione
XmlDocument()

Inizializza una nuova istanza della classe XmlDocument.

XmlDocument(XmlImplementation)

Inizializza una nuova istanza della XmlDocument classe con l'oggetto specificato XmlImplementation.

XmlDocument(XmlNameTable)

Inizializza una nuova istanza della XmlDocument classe con l'oggetto specificato XmlNameTable.

Proprietà

Nome Descrizione
Attributes

Ottiene un oggetto XmlAttributeCollection contenente gli attributi di questo nodo.

(Ereditato da XmlNode)
BaseURI

Ottiene l'URI di base del nodo corrente.

ChildNodes

Ottiene tutti i nodi figlio del nodo.

(Ereditato da XmlNode)
DocumentElement

Ottiene la radice XmlElement del documento.

DocumentType

Ottiene il nodo contenente la dichiarazione DOCTYPE.

FirstChild

Ottiene il primo elemento figlio del nodo.

(Ereditato da XmlNode)
HasChildNodes

Ottiene un valore che indica se il nodo dispone di nodi figlio.

(Ereditato da XmlNode)
Implementation

Ottiene l'oggetto XmlImplementation per il documento corrente.

InnerText

Genera un oggetto InvalidOperationException in tutti i casi.

InnerText

Ottiene o imposta i valori concatenati del nodo e di tutti i relativi nodi figlio.

(Ereditato da XmlNode)
InnerXml

Ottiene o imposta il markup che rappresenta gli elementi figlio del nodo corrente.

IsReadOnly

Ottiene un valore che indica se il nodo corrente è di sola lettura.

Item[String, String]

Ottiene il primo elemento figlio con l'oggetto e LocalNamespecificatoNamespaceURI.

(Ereditato da XmlNode)
Item[String]

Ottiene il primo elemento figlio con l'oggetto specificato Name.

(Ereditato da XmlNode)
LastChild

Ottiene l'ultimo elemento figlio del nodo.

(Ereditato da XmlNode)
LocalName

Ottiene il nome locale del nodo.

Name

Ottiene il nome completo del nodo.

NamespaceURI

Ottiene l'URI dello spazio dei nomi di questo nodo.

(Ereditato da XmlNode)
NameTable

Ottiene l'oggetto XmlNameTable associato a questa implementazione.

NextSibling

Ottiene il nodo immediatamente successivo a questo nodo.

(Ereditato da XmlNode)
NodeType

Ottiene il tipo del nodo corrente.

OuterXml

Ottiene il markup contenente questo nodo e tutti i relativi nodi figlio.

(Ereditato da XmlNode)
OwnerDocument

Ottiene l'oggetto XmlDocument a cui appartiene il nodo corrente.

ParentNode

Ottiene il nodo padre di questo nodo (per i nodi che possono avere elementi padre).

ParentNode

Ottiene l'elemento padre di questo nodo (per i nodi che possono avere elementi padre).

(Ereditato da XmlNode)
Prefix

Ottiene o imposta il prefisso dello spazio dei nomi di questo nodo.

(Ereditato da XmlNode)
PreserveWhitespace

Ottiene o imposta un valore che indica se mantenere lo spazio vuoto nel contenuto dell'elemento.

PreviousSibling

Ottiene il nodo immediatamente precedente a questo nodo.

(Ereditato da XmlNode)
PreviousText

Ottiene il nodo di testo che precede immediatamente questo nodo.

(Ereditato da XmlNode)
SchemaInfo

Restituisce il post-schema-Validation-Infoset (PSVI) del nodo.

Schemas

Ottiene o imposta l'oggetto associato all'oggetto XmlSchemaSetXmlDocument.

Value

Ottiene o imposta il valore del nodo.

(Ereditato da XmlNode)
XmlResolver

Imposta l'oggetto XmlResolver da utilizzare per la risoluzione delle risorse esterne.

Metodi

Nome Descrizione
AppendChild(XmlNode)

Aggiunge il nodo specificato alla fine dell'elenco dei nodi figlio di questo nodo.

(Ereditato da XmlNode)
Clone()

Crea un duplicato di questo nodo.

(Ereditato da XmlNode)
CloneNode(Boolean)

Crea un duplicato di questo nodo.

CreateAttribute(String, String, String)

Crea un oggetto XmlAttribute con l'oggetto , Prefixe LocalNamespecificatoNamespaceURI.

CreateAttribute(String, String)

Crea un oggetto XmlAttribute con il nome completo specificato e NamespaceURI.

CreateAttribute(String)

Crea un oggetto XmlAttribute con l'oggetto specificato Name.

CreateCDataSection(String)

Crea un oggetto XmlCDataSection contenente i dati specificati.

CreateComment(String)

Crea un oggetto XmlComment contenente i dati specificati.

CreateDefaultAttribute(String, String, String)

Crea un attributo predefinito con il prefisso, il nome locale e l'URI dello spazio dei nomi specificati.

CreateDocumentFragment()

Crea un oggetto XmlDocumentFragment.

CreateDocumentType(String, String, String, String)

Restituisce un nuovo XmlDocumentType oggetto.

CreateElement(String, String, String)

Crea un elemento con l'oggetto , Prefixe LocalNamespecificatoNamespaceURI.

CreateElement(String, String)

Crea un oggetto XmlElement con il nome completo e NamespaceURI.

CreateElement(String)

Crea un elemento con il nome specificato.

CreateEntityReference(String)

Crea un oggetto XmlEntityReference con il nome specificato.

CreateNavigator()

Crea un nuovo XPathNavigator oggetto per lo spostamento in questo documento.

CreateNavigator()

Crea un oggetto per l'esplorazione XPathNavigator di questo oggetto.

(Ereditato da XmlNode)
CreateNavigator(XmlNode)

Crea un XPathNavigator oggetto per spostarsi all'interno del documento posizionato sull'oggetto XmlNode specificato.

CreateNode(String, String, String)

Crea un oggetto XmlNode con il tipo di nodo specificato, Namee NamespaceURI.

CreateNode(XmlNodeType, String, String, String)

Crea un XmlNode oggetto con l'oggetto , XmlNodeType, Prefixe NamespecificatoNamespaceURI.

CreateNode(XmlNodeType, String, String)

Crea un oggetto XmlNode con l'oggetto , XmlNodeTypee NamespecificatoNamespaceURI.

CreateProcessingInstruction(String, String)

Crea un oggetto XmlProcessingInstruction con il nome e i dati specificati.

CreateSignificantWhitespace(String)

Crea un XmlSignificantWhitespace nodo.

CreateTextNode(String)

Crea un oggetto XmlText con il testo specificato.

CreateWhitespace(String)

Crea un XmlWhitespace nodo.

CreateXmlDeclaration(String, String, String)

Crea un XmlDeclaration nodo con i valori specificati.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetElementById(String)

Ottiene l'oggetto XmlElement con l'ID specificato.

GetElementsByTagName(String, String)

Restituisce un oggetto XmlNodeList contenente un elenco di tutti gli elementi discendenti che corrispondono all'oggetto e LocalNamespecificatoNamespaceURI.

GetElementsByTagName(String)

Restituisce un oggetto XmlNodeList contenente un elenco di tutti gli elementi discendenti corrispondenti all'oggetto specificato Name.

GetEnumerator()

Ottiene un enumeratore che scorre i nodi figlio nel nodo corrente.

(Ereditato da XmlNode)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetNamespaceOfPrefix(String)

Cerca la dichiarazione xmlns più vicina per il prefisso specificato nell'ambito del nodo corrente e restituisce l'URI dello spazio dei nomi nella dichiarazione.

(Ereditato da XmlNode)
GetPrefixOfNamespace(String)

Cerca la dichiarazione xmlns più vicina per l'URI dello spazio dei nomi specificato nell'ambito del nodo corrente e restituisce il prefisso definito in tale dichiarazione.

(Ereditato da XmlNode)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
ImportNode(XmlNode, Boolean)

Importa un nodo da un altro documento al documento corrente.

InsertAfter(XmlNode, XmlNode)

Inserisce il nodo specificato immediatamente dopo il nodo di riferimento specificato.

(Ereditato da XmlNode)
InsertBefore(XmlNode, XmlNode)

Inserisce il nodo specificato immediatamente prima del nodo di riferimento specificato.

(Ereditato da XmlNode)
Load(Stream)

Carica il documento XML dal flusso specificato.

Load(String)

Carica il documento XML dall'URL specificato.

Load(TextReader)

Carica il documento XML dall'oggetto specificato TextReader.

Load(XmlReader)

Carica il documento XML dall'oggetto specificato XmlReader.

LoadXml(String)

Carica il documento XML dalla stringa specificata.

MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
Normalize()

Inserisce tutti i nodi XmlText nella profondità completa del sottoalbero sottostante xmlNode in un formato "normale", in cui solo markup (ovvero tag, commenti, istruzioni di elaborazione, sezioni CDATA e riferimenti alle entità) separa i nodi XmlText, ovvero non sono presenti nodi XmlText adiacenti.

(Ereditato da XmlNode)
PrependChild(XmlNode)

Aggiunge il nodo specificato all'inizio dell'elenco di nodi figlio per questo nodo.

(Ereditato da XmlNode)
ReadNode(XmlReader)

Crea un XmlNode oggetto in base alle informazioni contenute in XmlReader. Il lettore deve essere posizionato su un nodo o un attributo.

RemoveAll()

Rimuove tutti i nodi figlio e/o gli attributi del nodo corrente.

(Ereditato da XmlNode)
RemoveChild(XmlNode)

Rimuove il nodo figlio specificato.

(Ereditato da XmlNode)
ReplaceChild(XmlNode, XmlNode)

Sostituisce il nodo oldChild figlio con newChild il nodo .

(Ereditato da XmlNode)
Save(Stream)

Salva il documento XML nel flusso specificato.

Save(String)

Salva il documento XML nel file specificato. Se il file specificato esiste, questo metodo lo sovrascrive.

Save(TextWriter)

Salva il documento XML nell'oggetto specificato TextWriter.

Save(XmlWriter)

Salva il documento XML nell'oggetto specificato XmlWriter.

SelectNodes(String, XmlNamespaceManager)

Seleziona un elenco di nodi corrispondenti all'espressione XPath. Tutti i prefissi trovati nell'espressione XPath vengono risolti usando l'oggetto fornito XmlNamespaceManager.

(Ereditato da XmlNode)
SelectNodes(String)

Seleziona un elenco di nodi corrispondenti all'espressione XPath.

(Ereditato da XmlNode)
SelectSingleNode(String, XmlNamespaceManager)

Seleziona la prima XmlNode che corrisponde all'espressione XPath. Tutti i prefissi trovati nell'espressione XPath vengono risolti usando l'oggetto fornito XmlNamespaceManager.

(Ereditato da XmlNode)
SelectSingleNode(String)

Seleziona la prima XmlNode che corrisponde all'espressione XPath.

(Ereditato da XmlNode)
Supports(String, String)

Verifica se l'implementazione DOM implementa una funzionalità specifica.

(Ereditato da XmlNode)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
Validate(ValidationEventHandler, XmlNode)

Convalida l'oggetto XmlNode specificato in base agli schemi XSD (XML Schema Definition Language) nella Schemas proprietà .

Validate(ValidationEventHandler)

Convalida l'oggetto in base agli XmlDocument schemi XSD (XML Schema Definition Language) contenuti nella Schemas proprietà .

WriteContentTo(XmlWriter)

Salva tutti gli elementi figlio del XmlDocument nodo nell'oggetto specificato XmlWriter.

WriteTo(XmlWriter)

Salva il XmlDocument nodo nell'oggetto specificato XmlWriter.

Eventi

Nome Descrizione
NodeChanged

Si verifica quando l'oggetto Value di un nodo appartenente a questo documento è stato modificato.

NodeChanging

Si verifica quando l'oggetto Value di un nodo appartenente a questo documento sta per essere modificato.

NodeInserted

Si verifica quando un nodo appartenente a questo documento è stato inserito in un altro nodo.

NodeInserting

Si verifica quando un nodo appartenente a questo documento sta per essere inserito in un altro nodo.

NodeRemoved

Si verifica quando un nodo appartenente a questo documento è stato rimosso dal relativo elemento padre.

NodeRemoving

Si verifica quando un nodo appartenente a questo documento sta per essere rimosso dal documento.

Implementazioni dell'interfaccia esplicita

Nome Descrizione
ICloneable.Clone()

Per una descrizione di questo membro, vedere Clone().

(Ereditato da XmlNode)
IEnumerable.GetEnumerator()

Per una descrizione di questo membro, vedere GetEnumerator().

(Ereditato da XmlNode)

Metodi di estensione

Nome Descrizione
AsParallel(IEnumerable)

Abilita la parallelizzazione di una query.

AsQueryable(IEnumerable)

Converte un IEnumerable in un IQueryable.

Cast<TResult>(IEnumerable)

Esegue il cast degli elementi di un IEnumerable al tipo specificato.

CreateNavigator(XmlDocument, XmlNode)

Crea un oggetto strumento di navigazione XPath per spostarsi nel documento specificato posizionato nel nodo specificato.

CreateNavigator(XmlDocument)

Crea un nuovo oggetto strumento di navigazione XPath per spostarsi nel documento specificato.

CreateNavigator(XmlNode)

Crea uno strumento di navigazione XPath per spostarsi nel nodo specificato.

OfType<TResult>(IEnumerable)

Filtra gli elementi di un IEnumerable in base a un tipo specificato.

SelectNodes(XmlNode, String, XmlNamespaceManager)

Seleziona un elenco di nodi corrispondenti all'espressione XPath specificata. Tutti i prefissi trovati nell'espressione XPath vengono risolti usando la gestione dello spazio dei nomi fornita.

SelectNodes(XmlNode, String)

Seleziona un elenco di nodi corrispondenti all'espressione XPath specificata.

SelectSingleNode(XmlNode, String, XmlNamespaceManager)

Seleziona il primo nodo che corrisponde all'espressione XPath. Tutti i prefissi trovati nell'espressione XPath vengono risolti usando la gestione dello spazio dei nomi fornita.

SelectSingleNode(XmlNode, String)

Seleziona il primo nodo che corrisponde all'espressione XPath.

ToXPathNavigable(XmlNode)

Crea un'istanza IXPathNavigable utilizzata per la produzione di strumenti di navigazione.

Si applica a

Vedi anche