xml element tree to html problem
Fredrik Lundh
fredrik at pythonware.com
Tue Apr 4 16:18:01 EDT 2006
Ron Adam wrote:
> I have an element tree structure of nested elements that I want to
> convert to html as nested definition and unordered lists in the
> following way.
>
> <object>
> <name>ball</ball>
> <desc>
> <color>red</color>
> <size>large</size>
> </desc>
> </object>
>
>
> To...
>
> <dl class='object'>
> <dt class='name'>ball</dt>
> <dd class='desc'>
> <ul>
> <li class='color'>red</li>
> <li class='size'>large</li>
> </ul>
> </dd>
> </dl>
>
>
> Where each xml tag has a predefined relationship to either definition
> list or an unordered list html tag. 'object' is always mapped to <dl
> class='object'>, 'name' is always mapped to <dt class='name'>. etc...
>
> So I will probably have a dictionary to look them up. The problem I
> have is finding a relatively painless way to do the actual translation.
here's one way to do it:
import cElementTree as ET
tree = ET.XML("""
<object>
<name>ball</name>
<desc>
<color>red</color>
<size>large</size>
</desc>
</object>
""")
MAP = {
"object": ("dl", "object"),
"name": ("dt", "name"),
"desc": ("ul", None),
"color": ("li", "color"),
"size": ("li", "size"),
}
for elem in tree.getiterator():
elem.tag, klass = MAP[elem.tag]
if klass:
elem.set("class", klass)
print ET.tostring(tree)
this prints:
<dl class="object">
<dt class="name">ball</dt>
<ul>
<li class="color">red</li>
<li class="size">large</li>
</ul>
</dl>
here's a somewhat simpler (but less general) version:
MAP = dict(object="dl", name="dt", desc="ul", color="li", size="li")
for elem in tree.getiterator():
if elem.tag != "desc":
elem.set("class", elem.tag)
elem.tag = MAP[elem.tag]
hope this helps!
</F>
More information about the Python-list
mailing list