使用XPath查询从匹配的XML节点获取属性值 [英] 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#代码获取值"文本
You can get the "the value" text with this C# code
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(text);
Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value);
这篇关于使用XPath查询从匹配的XML节点获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!