Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS parser + XHTML generator, advice needed

Guys, I need to develop a tool which would meet following requirements:

  1. Input: XHTML document with CSS rules within head section.
  2. Output: XHTML document with CSS rules computed in tag attributes

The best way to illustrate the behavior I want is as follows.

Example input:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <style type="text/css" media="screen">
    .a { color: red; }
        p { font-size: 12px; }
  </style>
</head>
<body>
    <p class="a">Lorem Ipsum</p>
    <div class="a">
         <p>Oh hai</p>
    </div>
</body>
</html>

Example output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<body>
    <p style="color: red; font-size: 12px;">Lorem Ipsum</p>
    <div style="color: red;">
         <p style="font-size: 12px;">Oh hai</p>
    </div>
</body>
</html>

What tools/libraries will fit best for such task? I'm not sure if BeautifulSoup and cssutils is capable of doing this.

Python is not a requirement. Any recommendations will be highly appreciated.

like image 318
ohnoes Avatar asked Apr 23 '09 11:04

ohnoes


3 Answers

Try premailer

code.dunae.ca/premailer.web

More info: campaignmonitor.com

like image 185
garrow Avatar answered Nov 15 '22 15:11

garrow


There is a premailer python package on Pypi

like image 1
Grégoire Cachet Avatar answered Nov 15 '22 15:11

Grégoire Cachet


While I do not know any specific tool to do this, here is the basic approach I would take:

Load as xml document
Extract the css classes and styles from document
For each pair of css class and style
  Construct xpath query from css class
  For each matching node
    Set the style attribute for that class
Remove style node from document Convert document to string

like image 1
Ross Goddard Avatar answered Nov 15 '22 15:11

Ross Goddard