這看起來不像應該很困難,但我目前陷入困境。我試圖從與給定XPath查詢字符串匹配的節點獲取特定屬性的屬性值。這是我到目前爲止有:使用XPath查詢從匹配的XML節點獲取屬性值
public static IEnumerable<string> GetAttributes(this XmlDocument xml,
string xpathQuery, string attributeName)
{
var doc = new XPathDocument(new XmlNodeReader(xml));
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr = nav.Compile(xpathQuery);
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext())
{
XPathNavigator curNav = iterator.Current;
if (curNav.HasAttributes)
{
XmlNode curNode = ((IHasXmlNode)curNav).GetNode();
if (null != curNode)
{
XmlAttribute attrib = curNode.Attributes[attributeName];
if (null != attrib)
{
yield return attrib.Value;
}
}
}
}
}
這目前拋出異常:
System.InvalidCastException:無法投類型的對象MS.Internal.Xml.Cache.XPathDocumentNavigator爲鍵入' System.Xml.IHasXmlNode」。
我該說這個錯嗎?有沒有更簡單的方法從匹配節點獲取屬性值?
爲什麼不使用LinqToXml?這會大大減少噪音,除非我錯過了Linq無法做到這一點的一些原因? – 2010-11-29 21:15:19