Partilhar via


Como: Usar Namespaces para XML na Associação de Dados

Exemplo

Este exemplo mostra como lidar com espaços para nome especificados no seu XML a origem de ligação.

If your XML data has the following XML namespace definition:

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">

You can use the XmlNamespaceMapping element to map the namespace to a Prefix, as in the following example. You can then use the Prefix to refer to the XML namespace. The ListBox in this example displays the title and dc:date of each item.

<StackPanel.Resources>
  <XmlNamespaceMappingCollection x:Key="mapping">
    <XmlNamespaceMapping Uri="http://purl.org/dc/elements/1.1/" Prefix="dc" />
  </XmlNamespaceMappingCollection>

  <XmlDataProvider Source="https://msdn.microsoft.com/subscriptions/rss.xml"
                   XmlNamespaceManager="{StaticResource mapping}"
                   XPath="rss/channel/item" x:Key="provider"/>

  <DataTemplate x:Key="dataTemplate">
    <Border BorderThickness="1" BorderBrush="Gray">
      <Grid Width="600" Height="50">
        <Grid.RowDefinitions>
          <RowDefinition Height="25"/>
          <RowDefinition Height="25"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="{Binding XPath=title}" />
        <TextBlock Grid.Row="1" Text="{Binding XPath=dc:date}" />
      </Grid>
    </Border>
  </DataTemplate>
</StackPanel.Resources>

<ListBox
  Width="600"
  Height="600"
  Background="Honeydew"
  ItemsSource="{Binding Source={StaticResource provider}}"
  ItemTemplate="{StaticResource dataTemplate}"/>

Note that the Prefix you specify does not have to match the one used in the XML source; if the prefix changes in the XML source your mapping still works.

In this particular example, the XML data comes from a web service, but the XmlNamespaceMapping element also works with inline XML or XML data in an embedded file.

Consulte também

Tarefas

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

Conceitos

Revisão de Associação de Dados

Outros recursos

Data Binding How-to Topics