使用XPath查询从匹配的XML节点获取属性值

这似乎不应该是困难的,但我现在卡住了。 我正在尝试从与给定XPath查询字符串匹配的节点获取特定属性的属性值。 这是我到目前为止所拥有的:

public static IEnumerable 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; } } } } } 

这目前抛出exception:

System.InvalidCastException:无法将“MS.Internal.Xml.Cache.XPathDocumentNavigator”类型的对象强制转换为“System.Xml.IHasXmlNode”。

我错了吗? 是否有更简单的方法从匹配节点获取属性值?

对于以下xml:

    

您可以使用此C#代码获取“值”文本

  XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(text); Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value); 

如果你使用.net 3.5或更高版本,你可以使用linq到Xml

对于给定的xml文档

                    

以下linq表达式将为您提供所有storedProcedure节点的“name”属性的值

 XDocument xDcoument = XDocument.Load(xmlStoredProcSchemeFile); var storedProcedureNames = from doc in xDcoument.Descendants("storedProcedure") select doc.Attribute("name").Value; 

您也可以使用常规的XPath语法。 在下面的代码中,变量节点保存由“usp_GET_HOME_PAGE_DATA”名称标识的节点,然后attributes变量保存所选节点及其子节点的所有子节点(属性)。

  XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(@"C:\inetpub\wwwroot\ASPNETBuilder\BusinessLayer\DataAccessCodeGenerationSchema.xml"); var node = xmlDocument.DocumentElement.SelectSingleNode("./storedProcedures/storedProcedure[@name='usp_GET_HOME_PAGE_DATA']"); var attributes = node.SelectNodes("./resultSet/@name"); 

解决抛出exception的初始问题…

 var doc = new XPathDocument(new XmlNodeReader(xml)); 

应该被……取代

 var doc = new XmlDocument(); doc.load(*you can either specify the path to the file, the string out of which the xml document is to be generated or specify an xmlreader, look for more overloads*); 

这不会抛出exception,代码也可以正常工作。