習慣了簡單的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();