What is the preferred XML processor to use with Python?
Some choices are
EDIT: I will need to be able to read in documents and manipulate them. I also require pretty print functionality.
lxml is where it's at.
Here's some example code:
import textwrap
from os.path import join
from lxml import etree
# string to Element
tree = etree.XML(textwrap.dedent('''
<foo_tag>
foo text
<bar_tag some_attr='ok'>bar text</bar_tag>
</foo_tag>
'''))
print 'root text: ' , tree.text
print 'pretty_print: '
print etree.tostring(tree, pretty_print=True)
print 'last child: (%s) (%s)' % (tree[-1].tag, tree[-1].text)
print
# filename to ElementTree
tree = etree.parse('some_file.xhtml')
def recurse(root, depth):
line = ' ' * depth + root.tag + ' {%s}' % ', '.join(root.attrib.keys())
if root.text:
line += ' <%s>' % root.text.strip()
print line
for child in root:
recurse(child, depth + 1)
print 'recurse tree:'
recurse(tree.getroot(), 0)
print
print 'find title: ', tree.findtext('html/head/title')
print 'find title again: ', tree.find('html').find('head').find('title').text
Here's some_file.xhtml which you can use for testing:
<?xml version="1.0" encoding="utf-8"?>
<root>
<metadata/>
<html>
<head>
<title style="bold">Page Title</title>
<span>Here's a <a href="google.com">link</a> to somewhere.</span>
</head>
<body bgcolor="#ffffff">Hello, World!</body>
</html>
</root>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With