Jython examples using Java XML classes

DocumentationAndEducation

TableOfContents


Examples related to Java XML classes using Jython will be here.

List of pages in this category:

Element tree

Here is a simple example. info on element tree is at http://effbot.org/zone/element-index.htm

Download element tree from http://effbot.org/downloads/

{{{from elementtree import ElementTree as ET root = ET.Element("html") head = ET.SubElement(root, "head") title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ffffff") body.text = "Hello, World!" tree = ET.ElementTree(root) tree.write("page.xhtml") import sys tree.write(sys.stdout)

which produces: {{{ <html><head><title>Page Title</title></head><body bgcolor="#ffffff">Hello, World !</body></html>>>> }}}

dom4j

This example requires http://www.dom4j.org/ the example below was tested with v1.6.1 download it and put it in you classpath.

This was posted to the Jython-users mailing list by Claude Falbriard Sep 14, 2007,

This simply prints out a xml tree. change line 39 to a valid xml filename.

import sys
from org.dom4j.io import SAXReader

def show_indent(level):
    return '    ' * level

def show_node(node, level):
    """Display one node in the DOM tree.
    """
    if node.getNodeType() == node.ELEMENT_NODE:
        name = node.getName()
        print '%sNode: %s' % (show_indent(level), name, )
        attrs = node.attributes()
        for attr in attrs:
            aName = attr.getQualifiedName()
            aValue = attr.getValue()
            print '  %sAttr -- %s: %s' % (show_indent(level), aName,aValue,)
    if node.getName() == 'RefNum':
        val = node.getText()
        print '%stitle: "%s"' % (show_indent(level+1), val, )
    elif node.getName() == 'link':
        val = node.getText()
        print '%slink    : "%s"' % (show_indent(level+1), val, )

    if node.getNodeType() == node.TEXT_NODE:
        print '**** text node'


def show_tree(node, level):
    show_node(node, level)
    level1 = level + 1
    children = node.elements()
    for child in children:
        show_tree(child, level1)

def test():
    print 'Version: %s' % (sys.version, )
    reader = SAXReader()
    doc = reader.read('example.xml')
    root = doc.getRootElement()
    show_tree(root, 0)

def main():
    test()

if __name__ == '__main__':
     main()