这似乎不应该是困难的,但我现在卡住了.我正在尝试从与给定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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这目前抛出异常:
System.InvalidCastException:无法将类型为"MS.Internal.Xml.Cache.XPathDocumentNavigator"的对象强制转换为"System.Xml.IHasXmlNode".
我错了吗?是否有更简单的方法从匹配节点获取属性值?