user2217039
user2217039

Reputation: 131

Read specific part of xml document with VB.NET

I guys, I have a xml with this model:

<XML>
  <IdValue id="1">
    <Value a="1" b="2" c="3" />
  </IdValue >
  <IdValue id="2">
    <Value a="10" b="20" c="30" />
  </IdValue >
</XML>

So i want to read, with a VB.NET program, the value of the attributes a, b, and c, in based on the value of the attribute id of the node IdValue.

Can yo help me ?

Thanks :)

Upvotes: 2

Views: 868

Answers (1)

sloth
sloth

Reputation: 101042

It's quite easy using VB.Net's XML literals and Linq-to-XML.

Given the following XML:

Dim xml = <XML>
            <IdValue id="1">
                <Value a="1" b="2" c="3" />
            </IdValue >
            <IdValue id="2">
                <Value a="10" b="20" c="30" />
            </IdValue >
           </XML>

You can extract the values you are looking for as easy as

Dim result = From id In xml.<IdValue>
             Select New With { .Id = id.@id,
                               .a  = id.<Value>.@a, 
                               .b  = id.<Value>.@b,
                               .c  = id.<Value>.@c }

For Each item in result
    Console.WriteLine(String.Format("id:{0} a:{1} b:{2} c:{3}", item.id, item.a, item.b, item.c))
Next

Output:

id:1 a:1 b:2 c:3
id:2 a:10 b:20 c:30

If you're interested in a single <IdValue>, you can add a Where clause; for example:

Dim result = From id In xml.<IdValue>
             Where id.@id = 2
             Select New With { .Id = id.@id,
                               .a  = id.<Value>.@a, 
                               .b  = id.<Value>.@b,
                               .c  = id.<Value>.@c }

Upvotes: 1

Related Questions