XPath 多个条件查询

时间:2022-10-23 19:21:03


习惯了简单的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();