XML Xpath on selecting on multiple attributes

I have XML that can look like either of the ones shown below

<?xml version="1.0" encoding="UTF-8"?>
<root>
	<record>
		<field cost="220"/>
	</record>
</root>

<?xml version="1.0" encoding="UTF-8"?>
<root>
	<record>
		<field val="220"/>
	</record>
</root>

Open in new window


I want to create and XPath to select either the 'cost' or the 'val' attribute.

Is there a better way than this ?

 /root/record/field/@val | /root/record/field/@cost 

Open in new window


Seems inefficient to me
MolkoAsked:
Who is Participating?
 
Geert BormansConnect With a Mentor Information ArchitectCommented:
note that there are quite a bunch of variants, depending on what can be found in the field elements

if they are not mutually exclusive you might want to do this to only pick the first

/root/record/field/@*[name() = 'cost' or name() = 'val'][1]

If only @cost or @val can happen
/root/record/field/@*
is sufficient

In XPath2.0 or higher you can exclude nodes from the selection

You see, whole bunch of options for rewrite
0
 
grayeCommented:
Uh, no... that's about it.

Why were you thinking it was inefficient?
0
 
Geert BormansInformation ArchitectCommented:
If your XPath version would be 2.0 or higher,
I would definitely do this
/root/record/field/(@cost | @val)

In most contexts that would be more efficient

Using XPath 1.0,
I have a tendency to rewrite the XPath as follows
/root/record/field/@*[name() = 'cost' or name() = 'val']
but the string casting of the name is expensive,
so it really depends on the optimisations used inside your XPath processor
So the efficiency gain is unpredictable
(you could run some tests if you want to know for your processor)
The Xpath looks definitely nicer in my opinion, but that is a matter of taste
0
 
MolkoAuthor Commented:
Thanks
0
 
Geert BormansInformation ArchitectCommented:
welcome
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.