こもろぐ @tenkoma

What We Find Changes Who We Become -- Peter Morville著『アンビエント・ファインダビリティ 』

広告:本ブログで紹介している書籍等商品の紹介でAmazonアソシエイトを利用していることがあります。

Python & DOM でXHTML生成

ローカルでHTML自動生成したくなったのでとりあえずxml.domパッケージを試しに使ってみる。

domtest.py

# -*- coding: cp932 -*-
from xml.dom import XHTML_NAMESPACE
from xml.dom.minidom import DocumentType, getDOMImplementation
dom = getDOMImplementation()
doctype = DocumentType('html')
doctype.publicId = "-//W3C//DTD XHTML 1.0 Strict//EN"
doctype.systemId = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
doc = dom.createDocument(XHTML_NAMESPACE, 'html', doctype)
 
html = doc.documentElement
html.setAttribute("xmlns",XHTML_NAMESPACE)
html.setAttribute("lang","ja")
html.setAttribute("xml:lang","ja")
 
head = doc.createElement("head")
html.appendChild(head)
 
title  = doc.createElement("title")
head.appendChild(title)
title_t = doc.createTextNode("DOM de XHTML")
title.appendChild(title_t)
 
body = doc.createElement("body")
html.appendChild(body)
 
h1 = doc.createElement("h1")
body.appendChild(h1)
h1_t = doc.createTextNode("ほげ Sample")
h1.appendChild(h1_t)
 
p = doc.createElement("p")
body.appendChild(p)
p_t = doc.createTextNode("Python HTMLGenerator")
p.appendChild(p_t)
 
print doc.toprettyxml(" ", "\n","UTF-8")

実行結果

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xml:lang="ja" xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>
   DOM de XHTML
  </title>
 </head>
 <body>
  <h1>
   ほげ Sample
  </h1>
  <p>
   Python HTMLGenerator
  </p>
 </body>
</html>
<||
疑問点など
-DOCTYPEの識別子を囲むのはシングルコーテーションでもいいんだっけ?ライブラリ(minidom.py)のソースコード見たらシングルかダブルか選べるようになってないようでしたorz
-html要素にlang属性とxml:lang属性を適用しようとしたら先に適用した方が消えた