CSSのセレクタをXPathに変換する
Warning! 2008/5/22追記:このエントリは情報が不十分だったり間違いが含まれてたりするので、下記URLのページを参考にするようにしてください↓
http://piro.sakura.ne.jp/latest/blosxom/mozilla/xul/2007-09-13_selector-to-xpath.htm
CSS3あたりをXPath1.0あたりに変換する表
CSS | XPath | |
.class | //*[@class="class"] | *1 |
.class | //*[contains(concat(" ",@class," ")," class ")] | *2 |
tag | //tag | |
#id | //*[@id="id"] | |
tag.class#id | //tag[@class="class"][@id="id"] | |
.class.class2 | //*[contains(concat(" ",@class," ")," class ") and contains(concat(" ",@class," ")," class2 ")] | |
tag tag2 | //tag//tag2 | |
tag > tag2 | //tag/tag2 | |
tag + tag2 | //tag/following-sibling::tag2 | |
tag[attr] | //tag[@attr] | |
tag[attr="val"] | //tag[@attr="val"] | |
tag[attr~="val"] | //tag[contains(concat(" ",@attr," ")," val ")] | |
tag[attr|="val"] | //tag[contains(concat("|",@attr,"|"),"|val|")] | |
tag[attr*="val"] | //tag[contains(@attr,"val")] | |
tag[attr^="val"] | //tag[starts-with(@attr,"val")] | |
tag[attr$="val"] | //tag[substring(@attr, string-length(@attr) - 2) = 'val')] | |
tag:first-child | //*[1]/self::tag | |
tag:last-child | //*[last()]/self::tag | |
tag:first-of-type | //tag[1] | |
tag:last-of-type | //tag[last()] | |
tag:only-of-type | //tag[count(../tag) = 1] | |
tag:empty | //tag[not(node())] | |
tag:nth-child(3) | //tag[count(preceding-sibling::*) = 3] | |
tag:nth-child(odd) | //tag[count(preceding-sibling::*) mod 2 = 0] | |
tag:nth-child(evenn) | //tag[count(preceding-sibling::*) mod 2 = 1] | |
tag:nth-child(3n) | //tag[count(preceding-sibling::*) mod 3 = 0] | |
tag:nth-last-child(2) | //tag[count(following-sibling::*) = 1] | |
tag:nth-of-type(odd) | //tag[position() mod 2 = 1] | |
*:root | /* | |
tag:contains("foo") | //tag[contains(text(), 'foo')] | |
tag:not([type="text"] | //tag[not(@type="text")] | |
*:not(tag) | //*[not(name="tag")] |
不可能ぽいもの
E:link, E:visited, E:active, E:hover, E:focus, E:target, E:lang(ja), E:enabled, E:disabled, E:checked, E:indeterminate, E::first-line, E::first-letter, E::selection, E::before, E::after
雑感
- 検証していないのもある
- 無理なのもある
- 疑似セレクタあたり
- かなり面倒なのもある
- XPath2.0というものもある http://www.w3.org/TR/xpath20/
- XPath2.0はかなり複雑な関数が含まれる http://www.w3.org/TR/xquery-operators/
- Google SpreadsheetのHTMLは汚い
- JavaScriptならこれで自動変換 → http://www.joehewitt.com/blog/2006-03-20.php
- perlならこれで自動変換 → http://search.cpan.org/dist/HTML-Selector-XPath/
- できないセレクタも多い