CSS selectors are a nice and intuitive alternative to XPath for DOM navigation. While XPath is more complete and has more functionality, CSS selectors were tailored for HTML DOM, where the document content is usually less structured than in XML.
Here are some examples of CSS selector and equivalent XPath expressions:
CSS: document > library > books > book
CSS: document book
CSS: document book#id3
CSS: document book[title='CSS for dummies']
XPath: //document//book[@title='CSS for dummies']
This becomes more interesting when implementing pseudo-selectors in XPath:
A very nice library that allows for parsing selector expressions according to the w3c specification
is this “css-selectors” by Christer Sandberg:
The next version of jOOX will include css-selector’s parser for simpler DOM navigation. The following two expressions will hold the same result:
Match match1 = $(document).find("book:empty");
Match match2 = $(document).xpath("//book[not(*|@*|node())]");
Published by lukaseder
I made jOOQ
View all posts by lukaseder
7 thoughts on “CSS selectors in Java”
Looking forward to CSS Selectors in JOOX ! Nice find on github !
Version 1.0.0 already partially supports CSS selectors in $(..).find(), e.g.
$(document).find(“books authors > author[name=Lukas]”);
Lukas, it seems that we are bumping into one another in the blogosphere! I started to look at alternative to XPath for testing in order to implement functionality in ActiveWeb that is similar to Ruby on Rails assert_select: assert_select.
I looked at the css-selectors by https://github.com/chrsan/css-selectors by Christer Sandberg and it seems like a perfect fit to test the views in ActiveWeb. However, I was unable to find it in Maven repository. Could you please share where you sourced it from?
Igor, yes, it’s a small world! :-)
Me too, I was thrilled to find a very comprehensive and standards-compliant CSS selector implementation in Java. I asked Christer if it was OK for me to include the relevant parts directly in jOOX, as I only needed the lexer / parser, not the execution facilities. Christer had no time so far to create a Maven Central artefact, but you could upvote adding css-selectors to Maven here:
Or, optionally, create a dependency on joox, if you only need the scanner, too. It is available here:
Lukas, thanks voting up!
Is there a way to derive the css selector given Dom node using jooq or any other lib?
Not right now. But I have created a feature request for this:
I’m currently not aware of any such library