Search code examples
xmlvb.netxelement

Parsing XML using XElement


I'm quite new to parsing XML using VB.NET. I have some XML in this format (simplified view)

<Range> 
<from>1</from> 
<to>5</to> 
</Range> 

<Range> 
<from>10</from> 
<to>20</to>
</Range>

<Range> 
<from>100</from> 
<to>200</to>
</Range>

There can be any amount of <Range> tags, but each Range tag will always have a <from> and <to> tag under it.

What I need to produce is a string, using the example above it will look something like this

1:1-5;2:10-20;3:100-200

I'm trying to use XElement to parse this, however not sure how to proceed. I tried iterating over using .Descendants("Range") which does give me the numbers but I can't separate out a from and to.

Any help will be much appreciated.

Thanks


Solution

  • Based on the data select all Range's and format. I used System.Text.StringBuilder in the example below.

        'your test data
        smpl = <root>
                   <Range>
                       <from>1</from>
                       <to>5</to>
                   </Range>
                   <Range>
                       <from>10</from>
                       <to>20</to>
                   </Range>
                   <Range>
                       <from>100</from>
                       <to>200</to>
                   </Range>
               </root>
    
        Dim sb As New System.Text.StringBuilder
        Dim ct As Integer = 1
        For Each r As XElement In smpl...<Range>
            sb.AppendFormat("{0}:{1}-{2};", ct, r.<from>.Value, r.<to>.Value)
            ct += 1
        Next
        sb.Remove(sb.Length - 1, 1)
    
        Dim s As String = sb.ToString
    

    After running s =

     1:1-5;2:10-20;3:100-200