1
votes

I am binding to an XML document in an XAML TextBlock statement and here is my XML document:

<Library>
    <Category Name="fiction">
        <Author Name="john Doe">
            <Book Title="Book A"/>
            <Book Title="Book B"/>
        </Author>
        <Author Name="Jane Doe"/>
    </Category>
    <Category Name="non-fiction"/>
    <Category Name="reference"/>
</Library>

In my xaml code, I can successfully bind to the Author "John Doe" using the following

Text="{Binding XPath=(/Library/Category/Author)[1]/@Name}" // Returns 'John Doe'.

However, if I try and bind to the first Book title (Book A) by John Doe using any of the following XPath statements, I get nothing.

Text="{Binding XPath=(/Library/Category/Author)[1]/(Book)[1]/@Title}" // Empty

Text="{Binding XPath=((/Library/Category/Author)[1]/Book)[1]/@Title}" //  Empty

Text="{Binding XPath=(/Library/Category/Author)[1]/Book[1]/@Title}" // Empty

Can someone tell me the correct syntax? Ideally, I want to be able to specify the Author by name rather index. Something like:

Text="{Binding XPath=((/Library/Category/Author)[@Name='john Doe']/Book)[1]/@Title}" //  Empty
1

1 Answers

0
votes

According to the XML sample posted, Book elmeents aren't children of Author but siblings. So in this case, you are supposed to use following-sibling axis instead :

  1. /Library/Category/Author[1]/following-sibling::Book[1]/@Title

  2. /Library/Category/Author[@Name='john Doe']/following-sibling::Book[1]/@Title *

Anyway, I would recommend changing the XML structure if possible. Place Book elements inside the corresponding Author parent element. This kind of structure is way easier to deal with using XPath. :

<Library>
    <Category Name="fiction">
        <Author Name="john Doe">
            <Book Title="Book A"/>
            <Book Title="Book B"/>
        </Author>
        <Author Name="Jane Doe"/>
    </Category>
    <Category Name="non-fiction"/>
    <Category Name="reference"/>
</Library>

And the XPath for the corrected XML :

  1. /Library/Category/Author[1]/Book[1]/@Title

  2. /Library/Category/Author[@Name='john Doe']/Book[1]/@Title *

*: Notice that XML & XPath are case-sensitive, here I assume you have 'john Doe' instead of proper-cased 'John Doe'.