这看起来不像应该很困难,但我目前陷入困境。我试图从与给定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