位置與條件篩選
索引選擇(1-based)
// 第一個 cd 子元素
/catalog/cd[1]
// 最後一個 cd
/catalog/cd[last()]
// 含有 price 子元素的 cd
/catalog/cd[price]
// price 值等於 10.90 的 cd
/catalog/cd[price=10.90]
// 符合條件 cd 的 price 元素
/catalog/cd[price=10.90]/price
多路徑合併(Union 操作符 |)
// 所有 title 和 artist
/catalog/cd/title | /catalog/cd/artist
// 文件中所有 title、artist、price(任意層級)
//title | //artist | //price
屬性查詢(@ 前綴)
// 所有 country 屬性
//@country
// 擁有 country 屬性的 cd 元素
//cd[@country]
// 擁有任意屬性的 cd
//cd[@*]
// country="UK" 的 cd
//cd[@country='UK']
實戰範例:XML 範例資料
<catalog>
<cd country="USA">
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<price>10.90</price>
</cd>
<cd country="UK">
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<price>9.90</price>
</cd>
</catalog>
C# 程式碼應用範例
var doc = new XmlDocument();
doc.Load("catalog.xml");
var navigator = doc.CreateNavigator();
// 選擇所有 UK 專輯標題
var iterator = navigator.Select("//cd[@country='UK']/title");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Value);
}
// 計算平均價格
var prices = navigator.Select("//cd/price");
double sum = 0; int count = 0;
while (prices.MoveNext())
{
sum += double.Parse(prices.Current.Value);
count++;
}
Console.WriteLine($"Average: {sum/count}");
XPath 2.0/3.0 新功能預覽
- 函數:
count(), sum(), avg(), distinct-values()
- 條件表達式:
if (...) then ... else ...
- 序列操作:
(1, 2, 3)[position() < 3]
- .NET 透過
Saxon 或 XmlPrime 支援
效能建議
- 避免
// 深度搜尋,改用具體路徑
- 編譯
XPathExpression 重用:navigator.Compile(xpath)
- 大量查詢考慮
XmlIndex 或轉換為 LINQ to XML