Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wishlist: Support writing XPath/XSLT functions in Ruby #336

Closed
hisashim opened this issue Sep 1, 2010 · 1 comment
Closed

Wishlist: Support writing XPath/XSLT functions in Ruby #336

hisashim opened this issue Sep 1, 2010 · 1 comment

Comments

@hisashim
Copy link

hisashim commented Sep 1, 2010

I wish Nokogiri allow us to write XPath/XSLT functions in Ruby.

Background: I have XML documents and I like to apply reasonably complicated context-dependent procedure (escaping, transcoding, etc.) to every text node in them, while transforming document tree structure.

Python lxml library has such feature:

Simplified usage example follows:

#!/usr/bin/ruby
# -*- encoding: utf-8 -*-

xml = <<EOXML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
 "http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="Content-type" content="application/xhtml+xml"/>
    <title>Foo</title>
  </head>
  <body>
    <h1>Foo</h1>
    <p>Lorem ipsum.</p>
  </body>
</html>
EOXML

xsl = <<EOXSL
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:f="http://exslt.org/functions"
  extension-element-prefixes="f">

  <xsl:template match="text()">
    <xsl:copy-of select="f:capitalize(.)"/>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:apply-imports/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
EOXSL

require 'nokogiri'
require 'stringio'

def capitalize(s)
  s.upcase
end
exts = {"f:capitalize" => method(:capitalize)}

xslt = Nokogiri::XSLT.parse(StringIO.new(xsl), :extensions => exts)
result = xslt.transform(Nokogiri::XML.parse(xml))
result.display

# expected output:
# <?xml version="1.0"?>
# <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
#   <head>
#     <meta http-equiv="Content-type" content="application/xhtml+xml"/>
#     <title>FOO</title>
#   </head>
#   <body>
#     <h1>FOO</h1>
#     <p>LOREM IPSUM.</p>
#   </body>
# </html>
@tenderlove
Copy link
Member

adding custom XSLT functions. closed by eb56525

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants