Compartilhar via


Como: Bind to XML Data Using an XMLDataProvider and XPath Queries

Este exemplo mostra como ligar a XML dados usando um XmlDataProvider.

With an XmlDataProvider, the underlying data that can be accessed through data binding in your application can be any tree of XML nodes. Em outras palavras, um XmlDataProvider fornece uma maneira conveniente de usar qualquer árvore de XML nós como um a origem de ligação.

Exemplo

No exemplo a seguir, os dados são incorporados diretamente como um XML a ilha de dados dentro do Resources seção. Um XML ilha de dados deve ser disposta em <x:XData> marcas e sempre ter um único nó raiz, que é estoque neste exemplo.

Observação

The root node of the XML data has an xmlns attribute that sets the XML namespace to an empty string.This is a requirement for applying XPath queries to a data island that is inline within the XAML page.In this inline case, the XAML, and thus the data island, inherits the System.Windows namespace.Because of this, you need to set the namespace blank to keep XPath queries from being qualified by the System.Windows namespace, which would misdirect the queries.

<StackPanel
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  Background="Cornsilk">

  <StackPanel.Resources>
    <XmlDataProvider x:Key="InventoryData" XPath="Inventory/Books">
      <x:XData>
        <Inventory >
          <Books>
            <Book ISBN="0-7356-0562-9" Stock="in" Number="9">
              <Title>XML in Action</Title>
              <Summary>XML Web Technology</Summary>
            </Book>
            <Book ISBN="0-7356-1370-2" Stock="in" Number="8">
              <Title>Programming Microsoft Windows With C#</Title>
              <Summary>C# Programming using the .NET Framework</Summary>
            </Book>
            <Book ISBN="0-7356-1288-9" Stock="out" Number="7">
              <Title>Inside C#</Title>
              <Summary>C# Language Programming</Summary>
            </Book>
            <Book ISBN="0-7356-1377-X" Stock="in" Number="5">
              <Title>Introducing Microsoft .NET</Title>
              <Summary>Overview of .NET Technology</Summary>
            </Book>
            <Book ISBN="0-7356-1448-2" Stock="out" Number="4">
              <Title>Microsoft C# Language Specifications</Title>
              <Summary>The C# language definition</Summary>
            </Book>
          </Books>
          <CDs>
            <CD Stock="in" Number="3">
              <Title>Classical Collection</Title>
              <Summary>Classical Music</Summary>
            </CD>
            <CD Stock="out" Number="9">
              <Title>Jazz Collection</Title>
              <Summary>Jazz Music</Summary>
            </CD>
          </CDs>
        </Inventory>
      </x:XData>
    </XmlDataProvider>
  </StackPanel.Resources>

  <TextBlock FontSize="18" FontWeight="Bold" Margin="10"
    HorizontalAlignment="Center">XML Data Source Sample</TextBlock>
  <ListBox
    Width="400" Height="300" Background="Honeydew">
    <ListBox.ItemsSource>
      <Binding Source="{StaticResource InventoryData}"
               XPath="*[@Stock='out'] | *[@Number>=8 or @Number=3]"/>
    </ListBox.ItemsSource>

    <!--Alternatively, you can do the following. -->
    <!--<ListBox Width="400" Height="300" Background="Honeydew"
      ItemsSource="{Binding Source={StaticResource InventoryData},
      XPath=*[@Stock\=\'out\'] | *[@Number>\=8 or @Number\=3]}">-->

    <ListBox.ItemTemplate>
      <DataTemplate>
        <TextBlock FontSize="12" Foreground="Red">
          <TextBlock.Text>
            <Binding XPath="Title"/>
          </TextBlock.Text>
        </TextBlock>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>
</StackPanel>

As shown in this example, to create the same binding declaration in attribute syntax you must escape the special characters properly. For more information, see Entidades e XAML de caractere XML.

The ListBox will show the following items when this example is run. Estes são o títulos de todos os elementos em livros com um um Stock valor de "check-out" ou um número valor de 3 ou maior que ou igual a 8. Observe que nenhum CD itens são retornados como a XPath conjunto de valor de XmlDataProvider indica que somente o livros elementos devem ser expostos (essencialmente definindo um filtro).

Exemplo de XPath

In this example, the book titles are displayed because the XPath of the TextBlock binding in the DataTemplate is set to "Title". If you want to display the value of an attribute, such as the ISBN, you would set that XPath value to "@ISBN".

The XPath properties in WPF are handled by the XmlNode.SelectNodes method. You can modify the XPath queries to get different results. Here are some examples for the XPath query on the bound ListBox from the previous example:

  • XPath="Book[1]" will return the first book element ("XML in Action"). Note that XPath indexes are based on 1, not 0.

  • XPath="Book[@*]" will return all book elements with any attributes.

  • XPath="Book[last()-1]" will return the second to last book element ("Introducing Microsoft .NET").

  • XPath="*[position()>3]" will return all of the book elements except for the first 3.

Quando você executa um XPath de consulta, ele retorna um XmlNode ou uma lista de XmlNodes. XmlNodeé um common language runtime (CLR) objeto, o que significa que você pode usar o Path propriedade para ligar o common language runtime (CLR) Propriedades. Consider the previous example again. If the rest of the example stays the same and you change the TextBlock binding to the following, you will see the names of the returned XmlNodes in the ListBox. In this case, the name of all the returned nodes is "Book".

<TextBlock FontSize="12" Foreground="Red">
  <TextBlock.Text>
    <Binding Path="Name"/>
  </TextBlock.Text>
</TextBlock>

In some applications, embedding the XML as a data island within the source of the XAML page can be inconvenient because the exact content of the data must be known at compile time. Therefore, obtaining the data from an external XML file is also supported, as in the following example:

<XmlDataProvider x:Key="BookData" Source="data\bookdata.xml" XPath="Books"/>

If the XML data resides in a remote XML file, you would define access to the data by assigning an appropriate URL to the Source attribute as follows:

<XmlDataProvider x:Key="BookData" Source="http://MyUrl" XPath="Books"/>

Consulte também

Tarefas

Como: Vincular XDocument, XElement ou LINQ para XML resultados de consulta

Como: Use the Master-Detail Pattern with Hierarchical XML Data

Referência

ObjectDataProvider

Conceitos

Visão geral sobre associação de fontes

Revisão de Associação de Dados

Outros recursos

Data Binding How-to Topics