VB.NET XML Parser - Find elements with specific attribute & value

蓝咒 提交于 2019-12-25 04:33:10

问题


HI,

I am using VB.NET to read an XHTML file. I need my program to find every element within the XML structure which has the "class" attribute set to a specific value.

IE: I need an array (or similar list) of all elements from the document which contain class="mytag".

There is a list of several values I need to detect, all of which start with the same word 'mytag' followed by another word - so using a "contains" function seems sensible here.

Any suggestions of ways I can parse out these attributes would be appreciated. Cheers.


回答1:


Use the following XPath expression with the SelectNodes function of an XmlDocument object:

//*[@class="mytag"]

This expression will select any XHTML element whose class attribute's value is equal to "mytag".

If you want to find all elements whose class attribute contains a particular string, the XPath function contains will help you:

//*[contains(@class,"mytag")]

The SelectNodes function returns a list of XML nodes from the XmlDocument corresponding on the XPath expression passed to it as a parameter. Based on your description, it's exactly what you need.




回答2:


If you are OK with LINQ try XML literals,

Like this:

Dim nodes = From currentNode In XmlDoc...<your-node-name>

For Each node As XElement In nodes

Console.Writeline(node.Attribute("attr-name").Value())

Next


来源:https://stackoverflow.com/questions/1471307/vb-net-xml-parser-find-elements-with-specific-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!