XPath 多条件查询语句

时间:2022-10-30 22:29:39

有这样一个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节点才会被搜索出来
有@的表示节点的属性,节点的value用text()=“”表示
data[text()=’Alpha’ and @type=’String’] 有这样(innertext = Alpha 且 type = String )的子节点才能被搜索出来
多个条件用and 连接

如果在加一层结点

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();