Shanthakumar
Shanthakumar

Reputation: 768

Select both attribute and content using xpath?

Xpath //a[contains(@class, 'storylink')]/@* will extract all attributes of anchor tags. Anchor tag in my xml doesn't have title attribute which usually have content of the link. Is there a way to select both href and text content in anchor link with XPATH 1.0 ?

Upvotes: 2

Views: 908

Answers (2)

Mads Hansen
Mads Hansen

Reputation: 66783

If you want to select both @href and text() in a single XPath selection, you can use the union operator |.

With XPath 1.0, this is probably the best you can do:

//a[contains(@class, 'storylink')]/@href | //a[contains(@class, 'storylink')]/text()

With XPath 2.0 (or higher) you could avoid repeating the anchor selection criteria:

//a[contains(@class, 'storylink')]/(@href,text())

Upvotes: 2

Michael Kay
Michael Kay

Reputation: 163458

Just select the a element itself using //a[contains(@class, 'storylink')] and then get the required attributes and/or text content using Javascript methods on the returned element node.

You could indeed select both the attributes and the text using XPath, but if they're all jumbled up in a single query result then it's a hassle separating them again.

Upvotes: 0

Related Questions