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"?>
		<field cost="220"/>

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

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
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Why were you thinking it was inefficient?
Gertone (Geert Bormans)Information 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
Gertone (Geert Bormans)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
is sufficient

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

You see, whole bunch of options for rewrite

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MolkoAuthor Commented:
Gertone (Geert Bormans)Information ArchitectCommented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.