XmlDataProvider Class

Enables declarative access to XML data for data binding.

Namespace:  System.Windows.Data
Assembly:  PresentationFramework (in PresentationFramework.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation, http://schemas.microsoft.com/netfx/2007/xaml/presentation

[LocalizabilityAttribute(LocalizationCategory.None, Readability = Readability.Unreadable)]
[ContentPropertyAttribute("XmlSerializer")]
public class XmlDataProvider : DataSourceProvider, 
	IUriContext
<XmlDataProvider>
  XmlSerializer
</XmlDataProvider>

The XmlDataProvider type exposes the following members.

  NameDescription
Public methodXmlDataProviderInitializes a new instance of the XmlDataProvider class.
Top

  NameDescription
Protected propertyBaseUri This type or member supports the WPF infrastructure and is not intended to be used directly from your code.
Public propertyDataGets the underlying data object. (Inherited from DataSourceProvider.)
Protected propertyDispatcherGets or sets the current Dispatcher object to the UI thread to use. (Inherited from DataSourceProvider.)
Public propertyDocumentGets or sets the XmlDocument to use as the binding source.
Public propertyErrorGets the error of the last query operation. (Inherited from DataSourceProvider.)
Public propertyIsAsynchronousGets or sets a value that indicates whether node collection creation will be performed in a worker thread or in the active context.
Public propertyIsInitialLoadEnabledGets or sets a value that indicates whether to prevent or delay the automatic loading of data. (Inherited from DataSourceProvider.)
Protected propertyIsRefreshDeferredGets a value that indicates whether there is an outstanding DeferRefresh in use. (Inherited from DataSourceProvider.)
Public propertySourceGets or sets the Uri of the XML data file to use as the binding source.
Public propertyXmlNamespaceManagerGets or sets the XmlNamespaceManager used to run XPath queries.
Public propertyXmlSerializerGets the inline XML content.
Public propertyXPathGets or sets the XPath query used to generate the data collection.
Top

  NameDescription
Protected methodBeginInitIndicates that initialization of this object is about to begin; no implicit Refresh occurs until the matched EndInit method is called. (Inherited from DataSourceProvider.)
Protected methodBeginQueryPrepares the loading of either the inline XML or the external XML file to produce a collection of XML nodes. (Overrides DataSourceProvider.BeginQuery().)
Public methodDeferRefreshEnters a defer cycle that you can use to change properties of the provider and delay automatic refresh. (Inherited from DataSourceProvider.)
Protected methodEndInitIndicates that the initialization of this element has completed; this causes a Refresh if no other DeferRefresh is outstanding. (Overrides DataSourceProvider.EndInit().)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitialLoadStarts the initial query to the underlying data model. The result is returned on the Data property. (Inherited from DataSourceProvider.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnPropertyChangedRaises the PropertyChanged event with the provided arguments. (Inherited from DataSourceProvider.)
Protected methodOnQueryFinished(Object)Derived classes call this method to indicate that a query has finished. (Inherited from DataSourceProvider.)
Protected methodOnQueryFinished(Object, Exception, DispatcherOperationCallback, Object)Derived classes call this method to indicate that a query has finished. (Inherited from DataSourceProvider.)
Public methodRefreshInitiates a refresh operation to the underlying data model. The result is returned on the Data property. (Inherited from DataSourceProvider.)
Public methodShouldSerializeSourceIndicates whether the Source property should be persisted.
Public methodShouldSerializeXmlSerializerIndicates whether the XmlSerializer property should be persisted.
Public methodShouldSerializeXPathIndicates whether the XPath property should be persisted.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public eventDataChangedOccurs when the Data property has a new value. (Inherited from DataSourceProvider.)
Protected eventPropertyChangedOccurs when a property value changes. (Inherited from DataSourceProvider.)
Top

  NameDescription
Explicit interface implemetationPrivate eventINotifyPropertyChanged.PropertyChangedOccurs when a property value changes. (Inherited from DataSourceProvider.)
Explicit interface implemetationPrivate methodISupportInitialize.BeginInitThis member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code. (Inherited from DataSourceProvider.)
Explicit interface implemetationPrivate methodISupportInitialize.EndInitThis member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code. (Inherited from DataSourceProvider.)
Explicit interface implemetationPrivate propertyIUriContext.BaseUriThis member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.
Top

Security noteSecurity Note

In a partial-trust sandbox, XmlDataProvider fails when it does not have permissions to access the given data. For more information about partial trust security, see WPF Partial Trust Security.

XmlDataProvider exposes the following ways to access XML data.

  • You can embed inline XML data using the XmlDataProvider class.

  • You can set the Source property to the Uri of an XML data file.

  • You can set the Document property to an XmlDocument.

XmlDataProvider performs a full refresh of all bindings when a XmlDocument.NodeChanged event occurs. There are no optimizations for specific nodes.

The XmlDataProvider.IsAsynchronous property is set to true by default, which means that the XmlDataProvider retrieves data and produces the collection of XML nodes asynchronously by default.

This example shows how to bind to XML data using an XmlDataProvider.

With an XmlDataProvider, the underlying data that can be accessed through data binding in your application can be any tree of XML nodes. In other words, an XmlDataProvider provides a convenient way to use any tree of XML nodes as a binding source.

In the following example, the data is embedded directly as an XML data island within the Resources section. An XML data island must be wrapped in <x:XData> tags and always have a single root node, which is Inventory in this example.

NoteNote

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="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Background="Cornsilk">

  <StackPanel.Resources>
    <XmlDataProvider x:Key="InventoryData" XPath="Inventory/Books">
      <x:XData>
        <Inventory xmlns="">
          <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 XML Character Entities and XAML.

The ListBox will show the following items when this example is run. These are the Titles of all of the elements under Books with either a Stock value of "out" or a Number value of 3 or greater than or equals to 8. Notice that no CD items are returned because the XPath value set on the XmlDataProvider indicates that only the Books elements should be exposed (essentially setting a filter).

XPath Example

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.

When you run an XPath query, it returns an XmlNode or a list of XmlNodes. XmlNode is a common language runtime (CLR) object, which means you can use the Path property to bind to the common language runtime (CLR) properties. 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"/>

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft