簡體   English   中英

使用多個索引綁定到XAML中的XML文檔

[英]Binding to XML doc in XAML with multiple indexes

我正在XAML TextBlock語句中綁定到XML文檔,這是我的XML文檔:

<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>

在我的xaml代碼中,我可以使用以下命令成功綁定到作者“ John Doe”

Text =“ {Binding XPath =(/ Library / Category / Author)[1] / @ Name}” //返回“ John Doe”。

但是,如果我嘗試使用以下XPath語句中的任何一個綁定到John Doe的第一個Book標題(Book A),那么我什么也沒得到。

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

有人可以告訴我正確的語法嗎? 理想情況下,我希望能夠通過名稱而不是索引來指定作者。 就像是:

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

根據發布的XML示例, Book Elmeent不是Author子代,而是兄弟姐妹。 因此,在這種情況下,您應該改用following-sibling軸:

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

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

無論如何,我建議盡可能更改XML結構。 Book元素放置在相應的Author父元素內。 使用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>

以及更正后的XML的XPath:

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

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

*:請注意,XML和XPath區分大小寫,這里我假設您使用的是'john Doe'而不是大小寫正確的'John Doe'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM