XPath 多个条件查询


习惯了简单的Xpath使用,碰到一个多个条件查询需求,研究了下。
把实现方式贴出来供大家参考:

有这样一个xml:
<?xml version=/"1.0/" encoding=/"ISO-8859-1/"?>
<Test>

<cell><data type="String">Alpha</data></cell>
<cell><data type="Number">100</data></cell>
<cell><data type="Number">200</data></cell>
<cell><data type="Boolean">true</data></cell>
</Test>

要求查找含有data节点满足type = String 且 inner text = Alpha 的所有cell 节点

Xpath 为: //cell[data[text()='Alpha'] and data[@type='String']]
或 //cell[data[text()='Alpha' and @type='String']]
分析下://cell表示搜索所有的cell节点
[]里面是条件,满足了这个条件的cell节点才会被搜索出来
data[text()='Alpha' and @type='String'] 有这样(innertext = Alpha 且 type = String )的子节点才能被搜索出来
多个条件用and 连接

如果在加一层结点呢?
<?xml version=/"1.0/" encoding=/"ISO-8859-1/"?>
<Test>
<Row>

<cell><data type="String">Alpha</data></cell>
<cell><data type="Number">100</data></cell>
<cell><data type="Number">200</data></cell>
<cell><data type="Boolean">true</data></cell>

</Row>
<Row>

<cell><data type="String1">Alpha</data></cell>
<cell><data type="Number1">100</data></cell>
<cell><data type="Number1">200</data></cell>
<cell><data type="Boolean1">true</data></cell>

</Row>
</Test>

要找孙子结点data 满足type = String 且 inner text = Alpha 的所有的Row结点

Xpath 为:
//row[cell/data[text()='Alpha'] and cell/data[@type='String']]

//row[cell/data[text()='Alpha' and @type='String']]

验证程序:

string xmlPayLoad = "<?xml version=/"1.0/" encoding=/"ISO-8859-1/"?>" +
"<test>" +
@"<row>" +
"<cell><data type=/"String/">Alpha</data></cell>" +
"<cell><data type=/"Number/">100</data></cell>" +
"<cell><data type=/"Number/">200</data></cell>" +
"<cell><data type=/"Boolean/"></data></cell>" +
"</row>" +
"<row>" +
"<cell><data type=/"String/">Gamma</data></cell>" +
"<cell><data type=/"Number/">12</data></cell>" +
"<cell><data type=/"Number/">25</data></cell>" +
"<cell><data type=/"Boolean/">1</data></cell>" +
"</row>" +
"</test>";
XmlDocument document = new XmlDocument();
document.LoadXml(xmlPayLoad);
string xmlPath = "//row[cell/data[text()='1'] and cell/data[@type='Boolean']]";
XmlNodeList nodeList = document.SelectNodes(xmlPath);
Console.WriteLine("nodeList.Count:" + nodeList.Count);
Console.ReadLine();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值