How to use XPath to make XML data binding

If you implement approach described in the article How to make XML nonhierarchical data binding, you can display only attributes values. You can get the text from nested elements by using XPath data binding expressions.

You can do this by using a template that defines XPath data binding expressions.  XPath data binding expressions are similar to Eval() expressions, except instead of supplying the name of the field you want to display, you supply an XPath expression based on the current node.

For example, here’s an XPath expression that starts at the current node, looks for a nested node named Title, and gets associated element text:

 

<%# XPath(“Title”)%>

 

As with the Eval() method, you can use an optional second parameter with a format string when calling XPath():

 

<%# XPath(“Price”, “{0:c}”) %>

 

The next markup lines show how to use GridView with a simple set of XPath expressions:

 

<asp:GridView ID=”GridView1″ runat=”server” DataSourceID=”sourceBooks” AutoGenerateColumns=”False”>

<Columns>

<asp:TemplateField HeaderText=”Book”>

<ItemTemplate>

<b><%# XPath(“@ISBN-13”) %></b>

<br />

<b><%# XPath(“@Title”) %></b>

<br />

<%# XPath(“Author”, “{0:c}” ) %>

<br />

<%# XPath(“Price”, “{0:c}” ) %>

<br />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

 

Note: Symbol @ is used in front of each attribute

The next picture shows the result

 

Using of XPath to make XML data binding

Using of XPath to make XML data binding