编写XPATH表达式

时间:2012-05-09 12:48:53

标签: c# xpath

您好,我有一个来自whihc的xml文件,我希望不会有它的一部分。那么,这是我的xml文件:

           <Item Text="Reports" Navigateurl ="Reports/Default.aspx">
  <Group>
    <Item Text="Customers" NavigateUrl="Reports/Customers/Default.aspx" Select="true">
      <Group>
        <Item Text="Customers" NavigateUrl="Reports/Customers/CustomerList.aspx" 
              Select="true"   />
        <Item Text="Customer Products" 
                    NavigateUrl="Reports/Customers/CustomersProducts.aspx" Select="true" />
        <Item Text="Customer Measurements" 
           NavigateUrl="Reports/Customers/CustomerLocationMeasurements.aspx" 
                Select="true"  />
        <Item Text="Customer Groups" NavigateUrl="Reports/Customers/CustomerGroups.aspx" />
        <Item Text="Customer Outages"  
             NavigateUrl="Reports/Customers/CustomerOutages.aspx" Select="true"/>
      </Group>
    </Item>

要选择此部分,我使用了以下表达式:

        XmlDataSource XmlDataSource1 = new XmlDataSource();
        XmlDataSource1.DataFile = "~/Menu.xml";
        XmlDataSource1.XPath = "//Item[@Text ='Customers']/Group";
        XmlDataSource1.DataBind();

结果将是

     Group
       Customers
       CustomerProducts
       ..........

但我只想要那些select属性为true的那些。但我还没有想到如何做到这一点。你能帮我吗?

3 个答案:

答案 0 :(得分:2)

不确定我是否正确记住了这一点 - 但我认为这是做到这一点的方法。

XmlDataSource1.XPath = "//Item[@Text ='Customers']/Group[/Item/@Select='true']";

答案 1 :(得分:0)

这是正确的方法:

XmlDataSource1.XPath = "//Item[@Text ='Customers']/Group/Item[@Select = 'true']";

答案 2 :(得分:0)

由于XPATH是XPATH,我已经在php中编写了这个例子,因为我的mac atm上没有c#编译器。

路径声明"//Item[@Text ='Customers'][@Select='true']"导致:

Reports/Customers/Default.aspx
Reports/Customers/CustomerList.aspx

示例代码:

<?php

$xml = <<<XML
<Item Text="Reports" Navigateurl ="Reports/Default.aspx">
    <Group>
        <Item Text="Customers" NavigateUrl="Reports/Customers/Default.aspx" Select="true">
            <Group>
                <Item Text="Customers" NavigateUrl="Reports/Customers/CustomerList.aspx" Select="true"   />
                <Item Text="Customer Products" NavigateUrl="Reports/Customers/CustomersProducts.aspx" Select="true" />
                <Item Text="Customer Measurements" NavigateUrl="Reports/Customers/CustomerLocationMeasurements.aspx" Select="true"  />
                <Item Text="Customer Groups" NavigateUrl="Reports/Customers/CustomerGroups.aspx" />
                <Item Text="Customer Outages" NavigateUrl="Reports/Customers/CustomerOutages.aspx" Select="true"/>
            </Group>
        </Item>
    </Group>
</Item>
XML;

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$list = $xpath->query("//Item[@Text ='Customers'][@Select='true']");
foreach($list as $item)
{
    printf("%s\n", $item->getAttribute('NavigateUrl'));
}