Wrox Programmer Forums
Go Back   Wrox Programmer Forums > XML > XML
|
XML General XML discussions.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the XML section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old April 7th, 2010, 12:33 PM
Registered User
 
Join Date: Apr 2010
Posts: 21
Thanks: 12
Thanked 0 Times in 0 Posts
Send a message via AIM to QuadFather
Question How to find attribute for specific element?

I'm programming in VB, using Visual Studio 2008.
This is a Windows Forms program.

GOAL: I want TextBox1 to display the <Calories> for the <Food> that matches the contents of ComboBox1 when I press Button1.


Objects I'm using:
  • ComboBox1
  • TextBox1
  • Button1

Here is my xml file (Foods.xml):
Code:
<?xml version="1.0" encoding="utf-8"?>
<Foods>
  <Food>
    <Name>BigMac (McDonald's)</Name>
    <Calories>485</Calories>
    <Fat>21.5</Fat>
  </Food>
</Foods>
Code I've tried:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim FoodCalories
        FoodCalories = XElement.Load("Foods.xml").<Food>.<Name>(ComboBox1.Text).<Calories>
        TextBox1 = FoodCalories
    End Sub
Doesn't work. Please help!
 
Old April 7th, 2010, 12:41 PM
Friend of Wrox
 
Join Date: Nov 2007
Posts: 1,243
Thanks: 0
Thanked 245 Times in 244 Posts
Default

You need to spend some hours on the LINQ to XML documentation; it is online at http://msdn.microsoft.com/en-us/library/bb387098.aspx but of course your Visual Studio documentation has the same section too, only accessible faster.
Code:
Dim food As XElement = XElement.Load("Foods.xml").<Food>.FirstOrDefault(Function(f) f.<Name>.Value = ComboBox1.Text)
If food IsNot Nothing Then
  TextBox1.Text = food.<Calories>.Value
Else
  ' treat the case here that no food was found
End If
__________________
Martin Honnen
Microsoft MVP (XML, Data Platform Development) 2005/04 - 2013/03
My blog
The Following User Says Thank You to Martin Honnen For This Useful Post:
QuadFather (April 7th, 2010)





Similar Threads
Thread Thread Starter Forum Replies Last Post
Finding if an attribute has a specific value mphare XSLT 1 February 2nd, 2009 06:57 PM
sort on specific attribute kgoldvas XSLT 2 July 17th, 2007 09:42 AM
Access specific Element and its Child elements! suersh79 XML 3 November 22nd, 2006 12:58 AM
Attribute for first element only mehdi62b XML 1 January 2nd, 2006 06:26 AM
How can I get the element node of an attribute cdias XSLT 2 March 15th, 2004 10:34 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.