XPath 多個條件查詢

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.