C# - 获取从匹配使用XPath查询XML节点属性值 [英] C# - get attribute values from matching XML nodes using XPath query
问题描述
这似乎并不像它应该是困难的,但我目前被困。我试图获取属性值从匹配给定的XPath查询字符串节点的特定属性。这是我到目前为止有:
This doesn't seem like it should be difficult, but I'm stuck currently. I'm trying to get the attribute values for a particular attribute from nodes that match a given XPath query string. Here's what I have so far:
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。
System.InvalidCastException: Unable to cast object of type 'MS.Internal.Xml.Cache.XPathDocumentNavigator' to type 'System.Xml.IHasXmlNode'.
我要对这个错误? ?有没有一种简单的方法来获得匹配的节点属性值
Am I going about this wrong? Is there a simpler way to get attribute values from matching nodes?
推荐答案
有关以下XML:
<root>
<elem att='the value' />
</root>
您可以使用此C#代码
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(text);
Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value);
这篇关于C# - 获取从匹配使用XPath查询XML节点属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!