嘗試:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
namespace XpathOp
{
class Program
{
static void Main(string[] args)
{
const string xml = @"<?xml version='1.0' encoding='ISO-8859-1'?>
<root>
<a>
<b/>
<c/>
</a>
<a>
<b/>
</a>
<a>
<d/>
<b/>
</a>
<a>
<d/>
<c/>
</a>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode node in doc.SelectNodes("//a[b or c]"))
{
Console.WriteLine("Founde node, name: {0}, hash: {1}", node.Name, node.GetHashCode());
}
XPathDocument xpathDoc = new XPathDocument(new MemoryStream(Encoding.UTF8.GetBytes(xml)));
XPathNavigator navi = xpathDoc.CreateNavigator();
XPathNodeIterator nodeIter = navi.Select("//a[b or c]");
foreach (XPathNavigator node in nodeIter)
{
IXmlLineInfo lineInfo = node as IXmlLineInfo;
Console.WriteLine("Found at line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition);
}
}
}
}
輸出:
Found node, name: a, hash: 62476613
Found node, name: a, hash: 11404313
Found node, name: a, hash: 64923656
Found node, name: a, hash: 44624228
Found at line 3, position 26
Found at line 7, position 26
Found at line 10, position 26
Found at line 14, position 26