tags:

views:

331

answers:

3

I have an xml document that is constructed pretty poorly-- instead of child nodes, the items have multiple attributes.

For Example:

<makes>
<option make="FORD" year_start="1950" year_end="2009" />
<option make="CHEVROLET" year_start="1965" year_end="2009" />
...
</makes>

I'm trying to use XPath to select the value of the other attributes for all nodes that match a certain attribute. I'm populating 3 asp drop down menus with values from 2 xml documents based on a previous selection. I'm using .net/c#

For Example: *for all option nodes with a make attribute that has the value x, find the value of year_start.*

I tried something like this:

  yearListData.XPath = string.Format("/makes/option[@year_start] and [@make={0}]", make);

where make = the previous selection. Obviously, it didn't work.

is there a way using XPath to do this?

+1  A: 
/makes/option[@make='FORD']/@year_start

...will get you all year_start attributes under options where the make is "FORD". Attributes are generally preferable to child elements if there's a 1-to-1 relationship--they don't require a verbose closing tag.

You might also consider linq to XML.

steamer25
+3  A: 
/makes/option[@year_start and @make="FORD"]/@year_start

You can combine with AND/OR conditions inside the [ and ], then ask for the attribute.

Remus Rusanu
The @year_start in the predicate is probably overkill, since it can't return something that doesn't exist, but it will give the right answer.
Marc Gravell
I left it in there to drive home the point that expressions can be combined in the predicate.
Remus Rusanu
Sarah Jean
@Sarah: http://msdn.microsoft.com/en-us/library/ms256086.aspx
Remus Rusanu
A: 

I don't know if this will work, but I think you could accomplish that with something like:


string.Format("/makes/option[@make={0}]//@year_start",make);
Freddy
You would need some quotes
Marc Gravell