Link to home
Start Free TrialLog in
Avatar of Molko
Molko

asked on

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
Avatar of graye
graye
Flag of United States of America image

Uh, no... that's about it.

Why were you thinking it was inefficient?
Avatar of Gertone (Geert Bormans)
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
ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Molko
Molko

ASKER

Thanks