Click here to Skip to main content
15,667,014 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I have the following XML string example:

<ProductVariantAttribute ID="6"><ProductVariantAttributeValue><Value>12</Value></ProductVariantAttributeValue></ProductVariantAttribute>		
<ProductVariantAttribute ID="1"><ProductVariantAttributeValue><Value>1</Value></ProductVariantAttributeValue></ProductVariantAttribute>		
<ProductVariantAttribute ID="3"><ProductVariantAttributeValue><Value>6</Value></ProductVariantAttributeValue></ProductVariantAttribute>

I need to get each ID= number and then the number between Value and do something in between getting each value.

I was able to get the number between Value using:

Dim xmlAtt As New XmlDocument()

Dim varIdCount As Integer = xmlAtt.DocumentElement.GetElementsByTagName("Value").Count
Dim y As Integer

For y = 0 To varIdCount - 1
    'varAttId = <GET ID NUMBER>
    varAttValue = xmlAtt.DocumentElement.GetElementsByTagName("Value").Item(i).InnerText

But I can't figure out how to get the attribute ID value at the same time.

Thanks in advance!!

1 solution


I'm not the most experienced person around here to answer this but I'll try.

First, I believe that the structure of you XML needs to looking into.

Do you expect more than 1 value in your ProductVariantAttributeValue element?

If not, then you could just leave out the Value element and put the real value in your ProductVariantAttributeValue element.

Otherwise, I'll have to adjust my code to accomodate.

But the following should do what you expect:

Imports System.Linq

Module Module1

    Sub Main()

        Dim query As IEnumerable(Of XElement) = From q In XML...<productvariantattribute> Select q

        For Each el In query
            Dim newAttr As New Attributes With {
                .ID = el.@ID,
                .Value = el...<value>.Value}


        For Each el In AttributesList
            Console.WriteLine("ID: " & el.ID)
            Console.WriteLine("Value: " & el.Value)

    End Sub

    Dim XML As XDocument =
            <productvariantattribute id="6">
            <productvariantattribute id="1">
            <productvariantattribute id="3">

    Dim AttributesList As New List(Of Attributes)
End Module

Public Class Attributes
    Property ID As String
    Property Value As String
End Class</value></productvariantattribute>

I create a class to hold your return values as I believe this is more inline with OOP.

Also, the XML read is done with linq because I'm a bit more familiar with it than using DOM elements.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900