XML Parse based on attribute ID

I'm new to using XML with visual basic. What I'm trying to accomplish is loading data into textboxes based on the items node. I have done that with static addresses. What I want to do now however is be able to change it based upon the attribute of the screen node called "ID".

For example if the attribute ID from the screen node = 36 I want aLabel.text to equal "Apples". I'll accept an answer in C# too, I can do either or.

XML Example

<Screen attribute ="35">
    <A>Chrono Trigger</A>
</Screen>
<Screen attribute ="36">
    <A>Apples</A>
</Screen>

VB.Net Code

 doc.Load(files)
 Static NodeNumber As Integer = 0
 RichTextBox1.Text = (doc.DocumentElement.SelectSingleNode("/Main/Screen").Attributes.ItemOf("ID").InnerText)
 aLabel.Text = (doc.DocumentElement.SelectSingleNode("/Main/Screen/A").InnerText)
 bLabel.Text = (doc.DocumentElement.SelectSingleNode("/Main/Screen/B").InnerText)
 cLabel.Text = (doc.DocumentElement.SelectSingleNode("/Main/Screen/C").InnerText)
 dLabel.Text = (doc.DocumentElement.SelectSingleNode("/Main/Screen/D").InnerText)

Upvotes: 0

Views: 153

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

You can use XPath to select the appropriate Screen element, like this

Dim screenNode as XmlNode = doc.SelectSingleNode("/Main/Screen[@attribute = '35']")

The part with the square brackets ([@attribute = '35']) is a condition--kind of like an If statement. The @ symbol is used to specify that you are specifying the name of an attribute rather than an element.

Then you can read the sub-elements like this:

aLabel.Text = screenNode.SelectSingleNode("A").InnerText
bLabel.Text = screenNode.SelectSingleNode("B").InnerText
cLabel.Text = screenNode.SelectSingleNode("C").InnerText
dLabel.Text = screenNode.SelectSingleNode("D").InnerText

XPath is a very powerful query language, with many other features. If you are going to be working with XML much, it would definitely recommend taking some time to at least learn its basics.

Upvotes: 1

Related Questions