使用XPath从XmlDataProvider过滤XML数据

时间:2013-01-25 17:42:48

标签: c# wpf xml xpath

我有一个xml这样的文件:

<Organizations xmlns="">
    <Organization  Title ="dfs" Score="70">
        <Layer  Title ="lar"></Layer>
    </Organization>
    <Organization  Title ="srwrg" Score="70">
        <Layer  Title ="asdf"></Layer>
        <Layer  Title ="lfdkj"></Layer>
    </Organization>
</Organizations>

我在WPF项目中使用此文件:(此处为资源)

<XmlDataProvider x:Key="myData" Source="Data\farsDataOrganization.xml" XPath="//Organizations/Organization"/>

<CollectionViewSource x:Key="MyCVS" >
        <CollectionViewSource.Source>
            <Binding Source="{StaticResource myData}"/>
        </CollectionViewSource.Source>
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="@Title" Direction="Ascending"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>

我知道如何根据组织的Title或图层Title进行过滤:

 XmlDataProvider p = (XmlDataProvider)this.FindResource("myData");
 p.XPath = string.Format("//Organizations/Organization[Layer[contains(@Title,\"{0}\")]]", this.layerNameFilter.Text);

但是我想根据组织的Title和图层Title来过滤这些数据。有什么建议吗?如何更改我的XPath字符串,以便根据这两个字符串获取过滤器?

修改

我在TreeView上显示这些数据:

 <TreeView Grid.Row="1" ItemsSource="{Binding Source={StaticResource MyCVS}}">
     <TreeView.Resources>
         <HierarchicalDataTemplate DataType="Organization" ItemsSource="{Binding XPath=Layer}">
             <StackPanel Orientation="Vertical" Width="340" Margin="0,0,0,5">
                 <Label Content="{Binding XPath=@Title}" FontSize="13" Margin="0,0,0,-5"></Label>
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

1 个答案:

答案 0 :(得分:3)

XmlDataProvider p = (XmlDataProvider)this.FindResource("myData");
p.XPath = string.Format("//Organizations/Organization[contains(@Title,\"{0}\")]/Layer[contains(@Title,\"{1}\")]", 
                        this.orgTitleFilter.Text, 
                        this.layerNameFilter.Text);