Converting A Single CSS Element Selector To XPath Using ColdFusion

Posted March 13, 2009 at 4:09 PM by Ben Nadel

Tags: ColdFusion

I wanted to explore the idea of converting natural CSS to XPath selectors for use in merging CSS with XHTML content. I don't think the concept is very complicated, but it does seem to have a bunch of little, moving parts. So, rather than solve all the problems at one time, I thought it would be good to break it down and start with the smallest problem first and then build on that to eventually convert natural CSS to XPath.

So, the smallest problem that I can see is converting a single element selector into XPath. For example, converting:

div

... into:

div

Or, converting:

div.form

... into:

div[ contains( @class, 'form' ) ]

This doesn't get into how these are grouped when it comes to contextual selecting (ex. P within a Div tag) - that's the next level up. Let's tackle the lowest level problem first, then we can worry about how to join these together to perform more complex searches.

When it comes to viable CSS selectors, I think we are dealing with about 6 different possibilties:

  • element#id
  • element.class
  • #id
  • .class
  • *.class
  • *

Thanks to the finite nature of this set, we can easily match these patterns against a simple CFIF / CFELSE statement with regular expressions. And so, I have taken that idea and wrapped it up in a ColdFusion user defined function, CSSElementSelectorToXPath():

  • <cffunction
  • name="CSSElementSelectorToXPath"
  • access="public"
  • returntype="string"
  • output="false"
  • hint="I convert a single element selector to XPath (ex. div.header).">
  •  
  • <!--- Define arguments. --->
  • <cfargument
  • name="Selector"
  • type="string"
  • required="true"
  • hint="I am the single element selector."
  • />
  •  
  • <!--- Define the local scope. --->
  • <cfset var LOCAL = {} />
  •  
  • <!---
  • Trim the selector and remove any pseudo selector
  • information. While some of these can be applied
  • (ex. :event), for our purposes, we are not going to
  • apply them at this time.
  • --->
  • <cfset LOCAL.Selector = Trim(
  • REReplace(
  • ARGUMENTS.Selector,
  • ":[^\s]*",
  • "",
  • "one"
  • )
  • ) />
  •  
  • <!---
  • Check to see what kind of pattern we have here. As far
  • as CSS is concerned, we really only have six different
  • selectors to care about:
  •  
  • element#id
  • element.class
  • #id
  • .class
  • *.class
  • *
  • --->
  • <cfif REFind( "^\w+##.+$", LOCAL.Selector )>
  •  
  • <!--- Return ID selector. --->
  • <cfreturn (
  • ListFirst( LOCAL.Selector, "##" ) &
  • "[ @id = """ &
  • ListLast( LOCAL.Selector, "##" ) &
  • """ ]"
  • ) />
  •  
  • <cfelseif REFind( "^\w+\..+$", LOCAL.Selector )>
  •  
  • <!--- Return class selector. --->
  • <cfreturn (
  • ListFirst( LOCAL.Selector, "." ) &
  • "[ contains( @class, """ &
  • ListLast( LOCAL.Selector, "." ) &
  • """ ) ]"
  • ) />
  •  
  • <cfelseif REFind( "^##.+$", LOCAL.Selector )>
  •  
  • <!--- Return ANY ID selector. --->
  • <cfreturn (
  • "*[ @id = """ &
  • ListLast( LOCAL.Selector, "##" ) &
  • """ ) ]"
  • ) />
  •  
  • <cfelseif REFind( "^\..+$", LOCAL.Selector )>
  •  
  • <!--- Return ANY class selector. --->
  • <cfreturn (
  • "*[ contains( @class, """ &
  • ListLast( LOCAL.Selector, "." ) &
  • """ ) ]"
  • ) />
  •  
  • <cfelseif REFind( "^\*\..+$", LOCAL.Selector )>
  •  
  • <!--- Return ANY class selector. --->
  • <cfreturn (
  • "*[ contains( @class, """ &
  • ListLast( LOCAL.Selector, "." ) &
  • """ ) ]"
  • ) />
  •  
  • <cfelseif REFind( "^\w+$", LOCAL.Selector )>
  •  
  • <!--- Return element selector. --->
  • <cfreturn LOCAL.Selector />
  •  
  • <cfelse>
  •  
  • <!--- Not valid - return ANY selector. --->
  • <cfreturn "*" />
  •  
  • </cfif>
  • </cffunction>

As you can see, I am stripping out any pseudo selectors before the conversion. It is true that some pseudo selectors can be used (ex. :even, :odd, :first), but for now, we'll strip them out. Really, it wouldn't be that hard to put them in; just as with the element selectors, each one would have to be mapped to a specific XPath predicate:

:first ==> [ position() = 1 ]

More on that late. Now, to test to see if the above UDF works, I am gonna run some various CSS selectors through it:

  • <cfoutput>
  •  
  • div ==>
  • #CSSElementSelectorToXPath( "div" )#<br />
  •  
  • div##data-form ==>
  • #CSSElementSelectorToXPath( "div##data-form" )#<br />
  •  
  • div.data-form ==>
  • #CSSElementSelectorToXPath( "div.data-form" )#<br />
  •  
  • ##data-form ==>
  • #CSSElementSelectorToXPath( "##data-form" )#<br />
  •  
  • .data-form ==>
  • #CSSElementSelectorToXPath( ".data-form" )#<br />
  •  
  • *.data-form ==>
  • #CSSElementSelectorToXPath( "*.data-form" )#<br />
  •  
  • </cfoutput>

When the above code, we get the following output:

div ==> div
div#data-form ==> div[ @id = "data-form" ]
div.data-form ==> div[ contains( @class, "data-form" ) ]
#data-form ==> *[ @id = "data-form" ) ]
.data-form ==> *[ contains( @class, "data-form" ) ]
*.data-form ==> *[ contains( @class, "data-form" ) ]

Looks like it's working nice. Next step will be to combine the above and create contextual selectors.




Reader Comments

There are no comments posted for this web log entry.

Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »