0

I have a code like this:

doc = Nokogiri::HTML("<a href='foo.html'>foo</a><a href='bar.html'>bar</a>")
doc.xpath('//a/@href').map(&:value) # => ["foo.html", "bar.html"]

It works as I expected.

But just out of curiosity I want to know, can I also get the value of href attributes only by using XPath?

ironsand
  • 14,329
  • 17
  • 83
  • 176
  • 3
    What do you mean `only by using XPath`? This `//a/@href` is `XPath` to get `href` attribute value. http://videlibri.sourceforge.net/cgi-bin/xidelcgi?&data=%3Ca%20href%3D%27foo.html%27%3Efoo%3C%2Fa%3E%3Ca%20href%3D%27bar.html%27%3Ebar%3C%2Fa%3E&=&extract=%2F%2Fa%2F%40href&=&input-format=auto&printed-node-format=text&output-format=adhoc&compatibility=Enable%20all%20extensions&dot-notation=unambiguous&extract-kind=xpath3 – Andersson Mar 20 '17 at 08:23
  • I thought maybe there is a xpath something like `//a/@href/value()`. It seems there isn't. Thanks. – ironsand Mar 20 '17 at 23:02

2 Answers2

0

Judging from the first answer to this question the answer seems to be yes and no. It offers

xml.xpath("//Placement").attr("messageId")

which is quite close to "only XPath", but not entirely. Up to you to judge if that is enough for you.

Community
  • 1
  • 1
Patru
  • 4,481
  • 2
  • 32
  • 42
0

Locate attributes first

example: site name: https://www.easymobilerecharge.com/

We want to locate "MTS" link

In your case, to locate this element, we can use x-path like: //a[contains(text(),'MTS')]

Now to get href attribute, use: //a[contains(text(),'MTS')]/@href

Anil Chandna
  • 180
  • 1
  • 9