How to: Use XML Namespaces in Data Binding


This example shows how to handle namespaces specified in your XML binding source.

If your XML data has the following XML namespace definition:

<rss version="2.0" xmlns:dc="">

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.

  <XmlNamespaceMappingCollection x:Key="mapping">
    <XmlNamespaceMapping Uri="" Prefix="dc" />

  <XmlDataProvider Source=""
                   XmlNamespaceManager="{StaticResource mapping}"
                   XPath="rss/channel/item" x:Key="provider"/>

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

  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.

See Also

Bind to XML Data Using an XMLDataProvider and XPath Queries
Data Binding Overview
How-to Topics