System.Xml.XmlDocument-Klasse

Dieser Artikel enthält ergänzende Hinweise zur Referenzdokumentation für diese API.

Die XmlDocument-Klasse ist eine Darstellung eines XML-Dokuments im Arbeitsspeicher. Sie implementiert DOM Level 1 Core und DOM Level 2 Core für das XML-Dokumentobjektmodell (DOM) von W3C.

DOM steht für Dokumentobjektmodell. Weitere Informationen hierzu finden Sie unter XML-Dokumentobjektmodell (DOM).

Sie können XML-Code mithilfe der XmlDocument-Klasse in das DOM laden und diesen anschließend im Dokument programmgesteuert lesen, ändern und entfernen.

Wenn Sie einen Einblick in die XmlDocument-Klasse und ihre Implementierung erhalten möchten, lesen Sie die Referenzquelle.

Laden von XML-Code in das Dokumentobjektmodell

Beginnen Sie mit einem XML-Dokument wie diesem, das einige Bücher in einer Sammlung enthält. Es weist den grundlegenden Inhalt eines beliebigen XML-Dokuments auf, einschließlich eines Namespace, Elemente, die Daten darstellen, und Attribute, die die Daten beschreiben.

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

Laden Sie als Nächstes diese Daten in das DOM, um damit im Arbeitsspeicher arbeiten zu können. Meistens wird hierfür auf eine Datei auf Ihrem lokalen Computer oder in einem Netzwerk verwiesen.

In diesem Beispiel wird XML-Code aus einer Datei geladen. Wenn die Datei nicht vorhanden ist, wird lediglich XML-Code generiert und geladen.

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

Weitere Informationen finden Sie unter Einlesen eines XML-Dokuments in das DOM.

Überprüfen anhand eines Schemas

Beginnen Sie mit einem XML-Schema wie diesem. Dieses Schema definiert die Datentypen im XML-Code sowie die erforderlichen Attribute.

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

Erstellen Sie ein XmlReader-Objekt mithilfe Ihres Schemas, und laden Sie dieses Objekt anschließend in das DOM. Erstellen Sie einen Ereignishandler, der ausgeführt wird, wenn Code versucht, Ihre XML-Datei auf eine Weise zu ändern, die gegen die Regeln des Schemas verstößt.

Diese Codeblöcke zeigen hierfür Hilfsmethoden an.

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

Weitere Informationen finden Sie unter Überprüfen eines XML-Dokuments im DOM.

Sie können mithilfe von Eigenschaften in einem XML-Dokument navigieren. Bevor Sie jedoch eine dieser Eigenschaften verwenden, sollten Sie kurz einige Begriffe überprüfen. Ihr Dokument besteht aus Knoten. Jeder Knoten verfügt über einen einzelnen übergeordneten Knoten direkt darüber. Der Stammknoten ist der einzige Knoten, der nicht über einen übergeordneten Knoten verfügt, da es sich um den Knoten der obersten Ebene handelt. Die meisten Knoten können untergeordnete Knoten aufweisen, die sich direkt unter ihnen befinden. Gleichgeordnete Knoten befinden sich auf derselben Ebene.

Die folgenden Beispiele zeigen, wie Sie den Stammknoten abrufen, zum ersten untergeordneten Knoten des Stammknotens navigieren, auf einen seiner untergeordneten Knoten zugreifen, zum übergeordneten Knoten zurückkehren und anschließend zwischen gleichgeordneten Knoten navigieren.

Beginnen mit dem Stammknoten

In diesem Beispiel wird der Stammknoten abgerufen und anschließend dazu verwendet, den Inhalt des Dokuments in der Konsole auszugeben.

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

Abrufen untergeordneter Knoten

Dieses Beispiel navigiert zum ersten untergeordneten Knoten des Stammknotens und durchläuft daraufhin die vorhandenen untergeordneten Knoten dieses Knotens.

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

Zurückkehren zum übergeordneten Knoten

Verwenden Sie die ParentNode-Eigenschaft.

Verweisen auf den letzten untergeordneten Knoten

In diesem Beispiel wird der Preis eines Buchs in die Konsole geschrieben. Der Preisknoten ist das letzte untergeordnete Element eines Buchknotens.

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

Vorwärtsnavigation über gleichgeordnete Knoten

Dieses Beispiel navigiert vorwärts von Buch zu Buch. Buchknoten sind gleichgeordnete Knoten.

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

Rückwärtsnavigation über gleichgeordnete Knoten

Dieses Beispiel navigiert rückwärts von Buch zu Buch.

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

Suchen von Knoten

Die am häufigsten verwendete Methode zum Auffinden eines oder mehrerer Datenknoten besteht darin, eine XPath-Abfragezeichenfolge zu verwenden, allerdings gibt es auch Methoden, die keine erfordern.

Abrufen eines einzelnen Knotens

In diesem Beispiel wird ein Buch mithilfe der ISBN-Nummer gesucht.

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

Die in diesem Beispiel verwendete Zeichenfolge ist eine XPath-Abfrage. Weitere Beispiele finden Sie in den XPath-Beispielen.

Sie können ebenfalls die GetElementById-Methode verwenden, um Knoten abzurufen. Um diesen Ansatz zu verwenden, müssen Sie die ID in den Definitionsdeklarationen für Dokumenttypen Ihrer XML-Datei definieren.

Nachdem Sie einen Knoten abgerufen haben, erhalten Sie den Wert von Attributen oder untergeordneten Knoten. In diesem Beispiel wird hierzu ein Buchknoten verwendet.

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

Abrufen einer Sammlung von Knoten

In diesem Beispiel werden alle Bücher ausgewählt, bei denen der Nachname des Autors oder der Autorin Austen ist. Anschließend wird der Preis dieser Bücher geändert.

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

Sie können eine Sammlung von Knoten ebenfalls abrufen, indem Sie den Namen des Knotens verwenden. In diesem Beispiel wird eine Sammlung aller Buchtitel abgerufen.

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

Weitere Informationen finden Sie unter Auswählen von Knoten mithilfe der XPath-Navigation.

Bearbeiten von Knoten

In diesem Beispiel werden ein Buchknoten und dessen Attribute bearbeitet.

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

Weitere Informationen finden Sie unter Ändern von Knoten, Inhalten und Werten in einem XML-Dokument.

Hinzufügen von Knoten

Verwenden Sie die Methoden CreateElement oder CreateNode, um einen Knoten hinzuzufügen.

Verwenden Sie die CreateElement-Methode, um einen Datenknoten wie ein Buch hinzuzufügen.

Verwenden Sie für jeden anderen Knotentyp wie ein Kommentar, Leerzeichenknoten oder CDATA-Knoten die CreateNode-Methode.

In diesem Beispiel wird ein Buchknoten erstellt, dem Attribute hinzugefügt werden und der anschließend dem Dokument hinzugefügt wird.

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

Weitere Informationen finden Sie unter Einfügen von Knoten in ein XML-Dokument.

Entfernen von Knoten

Verwenden Sie die RemoveChild-Methode, um einen Knoten zu entfernen.

In diesem Beispiel werden ein Buch aus dem Dokument sowie alle Leerzeichen entfernt, die unmittelbar vor dem Buchknoten angezeigt werden.

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

Weitere Informationen finden Sie unter Entfernen von Knoten, Inhalten und Werten aus einem XML-Dokument.

Positionieren von Knoten

Sie können mithilfe der Methoden InsertBefore und InsertAfter auswählen, wo ein Knoten in Ihrem Dokument angezeigt werden soll.

In diesem Beispiel werden zwei Hilfsmethoden veranschaulicht. Eine Methode verschiebt einen Knoten in einer Liste nach oben. Die andere verschiebt einen Knoten nach unten.

Diese Methoden könnten in einer Anwendung verwendet werden, mit der Benutzer*innen Bücher in einer Liste von Büchern nach oben und unten verschieben können. Wenn ein*e Benutzer*in ein Buch auswählt und auf die Schaltfläche „Nach oben“ oder „Nach unten“ klickt, könnte Ihr Code Methoden wie diese aufrufen, um den entsprechenden Buchknoten vor oder hinter andere Buchknoten zu verschieben.

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