XPathNavigator.Select Método

Definição

Seleciona um conjunto de nós, usando a expressão XPath especificada.

Sobrecargas

Name Description
Select(String)

Seleciona um conjunto de nós, usando a expressão XPath especificada.

Select(XPathExpression)

Seleciona um conjunto de nós usando o especificado XPathExpression.

Select(String, IXmlNamespaceResolver)

Seleciona um conjunto de nós usando a expressão XPath especificada com o IXmlNamespaceResolver objeto especificado para resolver prefixos de espaço de nomes.

Select(String)

Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs

Seleciona um conjunto de nós, usando a expressão XPath especificada.

public:
 virtual System::Xml::XPath::XPathNodeIterator ^ Select(System::String ^ xpath);
public virtual System.Xml.XPath.XPathNodeIterator Select(string xpath);
abstract member Select : string -> System.Xml.XPath.XPathNodeIterator
override this.Select : string -> System.Xml.XPath.XPathNodeIterator
Public Overridable Function Select (xpath As String) As XPathNodeIterator

Parâmetros

xpath
String

A String representa uma expressão XPath.

Devoluções

Um XPathNodeIterator apontar para o conjunto de nós selecionado.

Exceções

A expressão XPath contém um erro ou o seu tipo de retorno não é um conjunto de nós.

A expressão XPath não é válida.

Exemplos

O exemplo seguinte utiliza o Select método para selecionar um conjunto de nós.

XPathDocument document = new XPathDocument("books.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathNodeIterator nodes = navigator.Select("/bookstore/book");
nodes.MoveNext();
XPathNavigator nodesNavigator = nodes.Current;

XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Text, false);

while (nodesText.MoveNext())
    Console.WriteLine(nodesText.Current.Value);
Dim document As XPathDocument = New XPathDocument("books.xml")
Dim navigator As XPathNavigator = document.CreateNavigator()

Dim nodes As XPathNodeIterator = navigator.Select("/bookstore/book")
nodes.MoveNext()
Dim nodesNavigator As XPathNavigator = nodes.Current

Dim nodesText As XPathNodeIterator = nodesNavigator.SelectDescendants(XPathNodeType.Text, False)

While nodesText.MoveNext()
    Console.WriteLine(nodesText.Current.Value)
End While

O exemplo usa o books.xml arquivo como uma entrada.

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

Observações

O contexto para a seleção é a posição do XPathNavigator quando este método é chamado. Após chamar este método, o retornado XPathNodeIterator representa o conjunto de nós selecionados. Use MoveNext o método de para XPathNodeIterator iterar sobre o conjunto de nós selecionado.

O código C# seguinte itera sobre o conjunto selecionado de nós.

XPathNodeIterator iterator = nav.Select("/bookstore/book");
while (iterator.MoveNext())
{
    Console.WriteLine(Iterator.Current.Name);
}

Seguem-se as notas importantes a considerar ao utilizar o Select método.

Ver também

Aplica-se a

Select(XPathExpression)

Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs

Seleciona um conjunto de nós usando o especificado XPathExpression.

public:
 virtual System::Xml::XPath::XPathNodeIterator ^ Select(System::Xml::XPath::XPathExpression ^ expr);
public virtual System.Xml.XPath.XPathNodeIterator Select(System.Xml.XPath.XPathExpression expr);
abstract member Select : System.Xml.XPath.XPathExpression -> System.Xml.XPath.XPathNodeIterator
override this.Select : System.Xml.XPath.XPathExpression -> System.Xml.XPath.XPathNodeIterator
Public Overridable Function Select (expr As XPathExpression) As XPathNodeIterator

Parâmetros

expr
XPathExpression

Um XPathExpression objeto contendo a consulta XPath compilada.

Devoluções

E XPathNodeIterator isso aponta para o conjunto de nós selecionado.

Exceções

A expressão XPath contém um erro ou o seu tipo de retorno não é um conjunto de nós.

A expressão XPath não é válida.

Exemplos

O exemplo seguinte utiliza o Select método para selecionar um conjunto de nós.

XPathDocument document = new XPathDocument("books.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathExpression query = navigator.Compile("/bookstore/book");
XPathNodeIterator nodes = navigator.Select(query);
XPathNavigator nodesNavigator = nodes.Current;

XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Text, false);

while (nodesText.MoveNext())
{
    Console.WriteLine(nodesText.Current.Value);
}
Dim document As XPathDocument = New XPathDocument("books.xml")
Dim navigator As XPathNavigator = document.CreateNavigator()

Dim query As XPathExpression = navigator.Compile("/bookstore/book")
Dim nodes As XPathNodeIterator = navigator.Select(query)
Dim nodesNavigator As XPathNavigator = nodes.Current

Dim nodesText As XPathNodeIterator = nodesNavigator.SelectDescendants(XPathNodeType.Text, False)

While nodesText.MoveNext()
    Console.WriteLine(nodesText.Current.Value)
End While

O exemplo usa o books.xml arquivo como uma entrada.

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

Observações

O contexto para a seleção é a posição do XPathNavigator quando chamou este método. Depois de chamar este método, o retorno XPathNodeIterator representa o conjunto de nós selecionados. Use MoveNext no XPathNodeIterator para iterar sobre o conjunto de nós selecionado.

O código C# seguinte itera sobre o conjunto selecionado de nós.

XPathNodeIterator ni = nav.Select(expr);
while (ni.MoveNext())
{
    Console.WriteLine(ni.Current.Name);
}

Seguem-se as notas importantes a considerar ao utilizar o Select método.

Por exemplo, suponha que o documento contém os seguintes nós XML.

<bookstore xmlns:bk='urn:samples'>
    <book bk:ISBN='1-325-0980'>
        <title>Pride And Prejudice</title>
    </book>
</bookstore>

Neste caso, o seguinte código C# seleciona o bk:ISBN nó.

XPathExpression expr = nav.Compile("book/@bk:ISBN");
XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable());
mngr.AddNamespace("bk","urn:samples");
expr.SetContext(mngr);
XPathNodeIterator ni = nav.Select(expr);

Note

Se não XPathExpression incluir um prefixo, assume-se que o URI do namespace é o namespace vazio. Se o seu XML incluir um namespace por defeito, deve continuar a usar o SetContext método e fornecer um XmlNamespaceManager que contenha um prefixo e um URI de namespace para gerir o namespace por defeito.

Por exemplo, suponha que tem o seguinte XML.

<bookstore xmlns="http://www.lucernepublishing.com">
    <book>
        <title>Pride And Prejudice</title>
    </book>
</bookstore>

Neste caso, o seguinte código C# seleciona todos os nós livro:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com");
XPathExpression expr;
expr = nav.Compile("//ab:book");
expr.SetContext(nsmgr);
XPathNodeIterator ni = nav.Select(expr);

Este método não tem efeito no estado do XPathNavigator.

Ver também

Aplica-se a

Select(String, IXmlNamespaceResolver)

Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs
Origem:
XPathNavigator.cs

Seleciona um conjunto de nós usando a expressão XPath especificada com o IXmlNamespaceResolver objeto especificado para resolver prefixos de espaço de nomes.

public:
 virtual System::Xml::XPath::XPathNodeIterator ^ Select(System::String ^ xpath, System::Xml::IXmlNamespaceResolver ^ resolver);
public virtual System.Xml.XPath.XPathNodeIterator Select(string xpath, System.Xml.IXmlNamespaceResolver? resolver);
public virtual System.Xml.XPath.XPathNodeIterator Select(string xpath, System.Xml.IXmlNamespaceResolver resolver);
abstract member Select : string * System.Xml.IXmlNamespaceResolver -> System.Xml.XPath.XPathNodeIterator
override this.Select : string * System.Xml.IXmlNamespaceResolver -> System.Xml.XPath.XPathNodeIterator
Public Overridable Function Select (xpath As String, resolver As IXmlNamespaceResolver) As XPathNodeIterator

Parâmetros

xpath
String

A String representa uma expressão XPath.

resolver
IXmlNamespaceResolver

O IXmlNamespaceResolver objeto usado para resolver prefixos de espaço de nomes.

Devoluções

E XPathNodeIterator isso aponta para o conjunto de nós selecionado.

Exceções

A expressão XPath contém um erro ou o seu tipo de retorno não é um conjunto de nós.

A expressão XPath não é válida.

Exemplos

O exemplo seguinte ilustra a seleção de um conjunto de nós usando o Select método com o XmlNamespaceManager objeto especificado para resolver prefixos de espaço de nomes na expressão XPath.

XPathDocument document = new XPathDocument("contosoBooks.xml");
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("bk", "http://www.contoso.com/books");

XPathNodeIterator nodes = navigator.Select("/bk:bookstore/bk:book/bk:price", manager);
// Move to the first node bk:price node
if(nodes.MoveNext())
{
    // now nodes.Current points to the first selected node
    XPathNavigator nodesNavigator = nodes.Current;

    //select all the descendants of the current price node
    XPathNodeIterator nodesText =
       nodesNavigator.SelectDescendants(XPathNodeType.Text, false);

    while(nodesText.MoveNext())
    {
       Console.WriteLine(nodesText.Current.Value);
    }
}
Dim document As XPathDocument = New XPathDocument("contosoBooks.xml")
Dim navigator As XPathNavigator = document.CreateNavigator()

Dim manager As XmlNamespaceManager = New XmlNamespaceManager(navigator.NameTable)
manager.AddNamespace("bk", "http://www.contoso.com/books")

Dim nodes As XPathNodeIterator = navigator.Select("/bk:bookstore/bk:book/bk:price", manager)
' Move to the first node bk:price node.
If (nodes.MoveNext()) Then
    ' Now nodes.Current points to the first selected node.
    Dim nodesNavigator As XPathNavigator = nodes.Current

    ' Select all the descendants of the current price node.
    Dim nodesText As XPathNodeIterator = nodesNavigator.SelectDescendants(XPathNodeType.Text, False)

    While nodesText.MoveNext()
        Console.WriteLine(nodesText.Current.Value)
    End While
End If

O exemplo usa o contosoBooks.xml arquivo como uma entrada.

<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns="http://www.contoso.com/books">
    <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>

Aplica-se a