1 name1

Xml node value from attribute in VB.net

I have XML as

<Categories>
    <category name="a">
        <SubCategory>1</SubCategory>
        <SubCategoryName>name1</SubCategoryName>
    </category>
    <category name="b">
        <SubCategory>2</SubCategory>
        <SubCategoryName>name2</SubCategoryName>
    </category>
</Categories>

How to get value <SubCategoryName>from <category name="a">?

+5
source share
5 answers

As Usman recommended, you can use LINQ, but another popular option is to use XPath. You can use XPath to select the appropriate elements using a class XDocumentor an older class XmlDocument.

Here you can do it with XPath via the class XDocument:

Dim doc As New XDocument()
doc.Load(filePath)
Dim name As String = doc.XPathSelectElement("/Categories/category[@name='a']/SubCategoryName").Value

And here is how you do it with XPath through the class XmlDocument:

Dim doc As New XmlDocument()
doc.Load(filePath)
Dim name As String = doc.SelectSingleNode("/Categories/category[@name='a']/SubCategoryName").InnerText

Here's the meaning of parts of XPath:

  • /Categories- The slash at the beginning indicates that it is looking at the root of the XML document. After the slash follows the name of the subelement that we are looking for in the root.
  • /category - , /Categories.
  • [@name='a'] - , If. @, ( ).
  • /SubCategoryName - , category, .

XPath . XPath - , XML, XSLT, . , XML node . LINQ , Microsoft, LINQ , , XPath .

XPath //category[@name='a']/SubCategoryName. , .

+6

Dim xml = <Categories> 
                <category name="a"> 
                    <SubCategory>1</SubCategory> 
                    <SubCategoryName>name1</SubCategoryName> 
                </category> 
                <category name="b"> 
                    <SubCategory>2</SubCategory> 
                    <SubCategoryName>name2</SubCategoryName> 
                </category> 
               </Categories>

Dim result = xml.<category> _
                .First(Function(e) e.Attribute("name") = "a") _
                .<SubCategoryName>.Value

result name1.

0

 Dim doc As XDocument = XDocument.Load("YourXMLFileName")
 Dim query = From d In doc.Descendants("Categories").Elements("category")
                Where d.Attribute("name").Value = "a"
                Select d.Element("SubCategoryName").Value
0

:

Dim aux As New Xml.XmlDocument()
Dim nodeLst As Xml.XmlNodeList
Dim sResult As String = String.Empty

aux.Load(sXmlFilePath)
nodeLst = aux.GetElementsByTagName("category")

For Each cat As Xml.XmlElement In nodeLst
    If cat.GetAttribute("name") = "a" Then
        sResult = cat("SubCategoryName").Value
        Exit For
    End If
Next
0

,

sResult = cat("SubCategoryName").Value

sResult = cat("SubCategoryName").InnerText

0

All Articles