这似乎不应该是困难的,但我目前被卡住了。我正在尝试从与给定 XPath 查询字符串匹配的节点中获取特定属性的属性值。这是我到目前为止所拥有的:
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”类型。
我要解决这个问题了吗?有没有更简单的方法从匹配节点获取属性值?