Partager via


Extraire des données XML à l’aide de XPathNavigator

Il existe plusieurs façons de représenter un document XML dans Microsoft .NET Framework. Cela inclut l’utilisation de String, ou à l’aide des classes XmlReader, XmlWriter, XmlDocument, ou XPathDocument. Pour faciliter le déplacement entre ces différentes représentations d’un document XML, la XPathNavigator classe fournit un certain nombre de méthodes et de propriétés pour extraire le code XML en tant qu’objet Stringou XmlReaderXmlWriter objet.

Convertir un XPathNavigator en chaîne

La OuterXml propriété de la XPathNavigator classe est utilisée pour obtenir le balisage de l’intégralité du document XML ou simplement le balisage d’un nœud unique et de ses nœuds enfants.

Remarque

La propriété InnerXml n'obtient le balisage que des nœuds enfants d'un nœud.

L’exemple de code suivant montre comment enregistrer un document XML entier contenu dans un XPathNavigator objet String, ainsi qu’un nœud unique et ses nœuds enfants.

Dim document As XPathDocument = New XPathDocument("input.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
' Save the entire input.xml document to a string.  
Dim xml As String = navigator.OuterXml  
  
' Now save the Root element and its child nodes to a string.  
navigator.MoveToChild(XPathNodeType.Element)  
Dim root As String = navigator.OuterXml  
XPathDocument document = new XPathDocument("input.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
// Save the entire input.xml document to a string.  
string xml = navigator.OuterXml;  
  
// Now save the Root element and its child nodes to a string.  
navigator.MoveToChild(XPathNodeType.Element);  
string root = navigator.OuterXml;  

Convertir un XPathNavigator en XmlReader

La ReadSubtree méthode est utilisée pour diffuser en continu l’intégralité du contenu d’un document XML ou simplement un seul nœud et ses nœuds enfants vers un XmlReader objet.

Lorsque l’objet XmlReader est créé avec le nœud actuel et ses nœuds enfants, la propriété XmlReader de l’objet ReadState est définie à Initial. Lorsque la méthode XmlReader de l'objet Read est appelée pour la première fois, le XmlReader est déplacé vers le nœud actuel du XPathNavigator. Le nouvel XmlReader objet continue de lire jusqu’à ce que la fin de l’arborescence XML soit atteinte. À ce stade, la Read méthode retourne false et la propriété de l’objet XmlReaderReadState est définie sur EndOfFile.

La XPathNavigator position de l’objet n’est pas modifiée par la création ou le mouvement de l’objet XmlReader . La ReadSubtree méthode est valide uniquement lorsqu’elle est positionnée sur un élément ou un nœud racine.

L’exemple suivant montre comment obtenir un XmlReader objet contenant l’intégralité du document XML dans un XPathDocument objet, ainsi qu’un nœud unique et ses nœuds enfants.

Dim document As XPathDocument = New XPathDocument("books.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
' Stream the entire XML document to the XmlReader.  
Dim xml As XmlReader = navigator.ReadSubtree()  
  
While xml.Read()  
    Console.WriteLine(xml.ReadInnerXml())  
End While  
  
xml.Close()  
  
' Stream the book element and its child nodes to the XmlReader.  
navigator.MoveToChild("bookstore", "")  
navigator.MoveToChild("book", "")  
  
Dim book As XmlReader = navigator.ReadSubtree()  
  
While book.Read()  
    Console.WriteLine(book.ReadInnerXml())  
End While  
  
book.Close()  
XPathDocument document = new XPathDocument("books.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
// Stream the entire XML document to the XmlReader.  
XmlReader xml = navigator.ReadSubtree();  
  
while (xml.Read())  
{  
    Console.WriteLine(xml.ReadInnerXml());  
}  
  
xml.Close();  
  
// Stream the book element and its child nodes to the XmlReader.  
navigator.MoveToChild("bookstore", "");  
navigator.MoveToChild("book", "");  
  
XmlReader book = navigator.ReadSubtree();  
  
while (book.Read())  
{  
    Console.WriteLine(book.ReadInnerXml());  
}  
  
book.Close();  

L’exemple prend le fichier books.xml comme entrée.

<?xml version="1.0" encoding="utf-8" ?> 
<bookstore>
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

Conversion d’un XPathNavigator en XmlWriter

La WriteSubtree méthode est utilisée pour diffuser en continu l’intégralité du contenu d’un document XML ou simplement un seul nœud et ses nœuds enfants vers un XmlWriter objet.

La XPathNavigator position de l’objet n’est pas modifiée par la création de l’objet XmlWriter .

L’exemple suivant montre comment obtenir un XmlWriter objet contenant l’intégralité du document XML dans un XPathDocument objet, ainsi qu’un nœud unique et ses nœuds enfants.

Dim document As XPathDocument = New XPathDocument("books.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
' Stream the entire XML document to the XmlWriter.  
Dim xml As XmlWriter = XmlWriter.Create("newbooks.xml")  
navigator.WriteSubtree(xml)  
xml.Close()  
  
' Stream the book element and its child nodes to the XmlWriter.  
navigator.MoveToChild("bookstore", "")  
navigator.MoveToChild("book", "")  
  
Dim book As XmlWriter = XmlWriter.Create("book.xml")  
navigator.WriteSubtree(book)  
book.Close()  
XPathDocument document = new XPathDocument("books.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
// Stream the entire XML document to the XmlWriter.  
XmlWriter xml = XmlWriter.Create("newbooks.xml");  
navigator.WriteSubtree(xml);  
xml.Close();  
  
// Stream the book element and its child nodes to the XmlWriter.  
navigator.MoveToChild("bookstore", "");  
navigator.MoveToChild("book", "");  
  
XmlWriter book = XmlWriter.Create("book.xml");  
navigator.WriteSubtree(book);  
book.Close();  

L’exemple prend le books.xml fichier trouvé précédemment dans cette rubrique comme entrée.

Voir aussi