当前位置: 首页 > 编程语言 > C#

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

时间:2023-04-10 18:39:22 C#

使用XPath查询从匹配的XML节点中获取属性值这看起来并不难,但我卡住了现在。我正在尝试从与给定XPath查询字符串匹配的节点中获取特定属性的属性值。这是我到目前为止所拥有的:XPathNavigatornav=doc.CreateNavigator();XPathExpressionexpr=nav.Compile(xpathQuery);XPathNodeIteratoriterator=nav.Select(expr);while(iterator.MoveNext()){XPathNavigatorcurNav=iterator.Current;如果(curNav.HasAttributes){XmlNodecurNode=((IHasXmlNode)curNav).GetNode();if(null!=curNode){XmlAttributeattrib=curNode.Attributes[attributeName];if(null!=attrib){yieldreturnattrib.Value;}}}}}这当前抛出异常:System.InvalidCastException:无法将“MS.Internal.Xml.Cache.XPathDocumentNavigator”类型的对象转换为“System.Xml.IHasXmlNode”。我错了吗?有没有更简单的方法从匹配节点获取属性值?对于以下xml:您可以使用此C#代码获取“值”文本XmlDocumentxdoc=newXmlDocument();xdoc.LoadXml(文本);Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value);如果您使用.net3.5或更高版本,则可以使用linqtoXml对于给定的xml文档,以下linq表达式将为您提供所有storedProcedure节点的“名称”属性的值XDocumentxDcoument=XDocument.Load(xmlStoredProcSchemeFile);varstoredProcedureNames=fromdocinxDcoument.Descendants("storedProcedure")selectdoc.Attribute("name").Value;您还可以使用常规的XPath语法。在下面的代码中,变量node保存由“usp_GET_HOME_PAGE_DATA”名称标识的节点,然后attributes变量保存所选节点及其子节点的所有子节点(属性)。XmlDocumentxmlDocument=newXmlDocument();xmlDocument.Load(@"C:inetpubwwwrootASPNETBuilderBusinessLayerDataAccessCodeGenerationSchema.xml");varnode=xmlDocument.DocumentElement.SelectSingleNode("./storedProcedures/storedProcedure[@name='usp_GET_HOME_PAGEs)_DATA']"atvar']=node.SelectNodes("./resultSet/@name");解决最初抛出异常的问题...vardoc=newXPathDocument(newXmlNodeReader(xml));应替换为...vardoc=newXmlDocument();doc.load(*您可以指定文件的路径,生成xml文档的字符串或指定xmlreader,寻找更多重载*);这不会引发异常并且代码工作正常。以上就是C#学习教程:使用XPath查询从匹配的XML节点中获取属性值共享的全部内容。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: