これは難しいことではないようですが、私は現在立ち往生しています。特定の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」にキャストできません。
私はこれについて間違っていますか?一致するノードから属性値を取得する簡単な方法はありますか?