Skip to content

Instantly share code, notes, and snippets.

@mikepfirrmann
Created March 13, 2013 15:33
Show Gist options
  • Save mikepfirrmann/5153260 to your computer and use it in GitHub Desktop.
Save mikepfirrmann/5153260 to your computer and use it in GitHub Desktop.
Demonstration of accessing a namespaced attribute of an SVG nested within HTML using Nokogiri.
#!/usr/bin/env ruby
require 'nokogiri'
puts "Using Nokogiri version: #{Nokogiri::VERSION}"
# HTML5 document with inline SVG.
html = <<-HTML
<!DOCTYPE html>
<html>
<head>
<title>Attribute Access Test</title>
</head>
<body>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="550"
height="190"
viewbox="0 0 550 190"
>
<image
xlink:href="https://www.google.com/images/srpr/logo4w.png"
width="550"
height="190"
/>
</svg>
</body>
</html>
HTML
doc = Nokogiri::HTML(html)
image = doc.css('image').first
# This results in nil in Nokogiri > 1.5.5.
puts "image['xlink:href'] == #{image['xlink:href'].inspect}"
# This results in the actual value of the attribute.
puts "image.attribute('xlink:href') == #{image.attribute('xlink:href').value.inspect}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment