-
Notifications
You must be signed in to change notification settings - Fork 1
Home
xmltramp is a Python library based on xml.sax that simplifies handling XML documents.
doc = xmltramp.parse("<foo version='1'><bar name='foobar'/></foo>")
doc = xmltramp.seed(open("test.xml"))
doc = xmltramp.load("http://rss.slashdot.org/Slashdot/slashdot")
Each node is represented by a xmltramp.Element instance.
A node's text content can be read with unicode(elt), which returns a
Unicode string (duh!), or with str(elt), which returns a plain ASCII string
with XML character references where needed.
A node's attributes can be read with the call syntax elt(attrname),
so doc('version') returns '1'. elt() without parameters returns a dictionary
of all attributes and their values.
Child nodes are read with array subscript syntax.
-
node['subtag']returns the first<subtag>child ofnode, sodoc['bar']returns the<bar>node. - To iterate over all child nodes with a given tag, use a slice:
node[tagname:]returns a list of all 'tagname' children ofnode. - To iterate over all child nodes regardless of their tag, use the empty slice:
node[:]returns a list of all children ofnode. - A numeric index
nreturns the n-th child node. - Numeric slices return the expected subset of child nodes.
Start by creating the root node:
root = Element('foo')
or by parsing a template XML document.
The Element constructor takes these keyword parameters:
-
attrs, a dict of node attributes -
children, a list of child nodes (themselvesElements or strings) -
value:- a string that becomes the node's text content
- a list of attribute name, value pairs (not tuples!)
- a dict of attributes
A node's children can be changed using array subscript syntax again:
-
node["bar"] = xreplaces the firstbarchild with x and deletes all otherbarchildren -
node["bar":] = xappends a newbarnode with content x -
node[0] = xreplaces the first subnode with x -
node[None] = xappends x tonode's children. x may be a string or anElementinstance.
x is interpreted like the value constructor parameter.
A node's attributed can be changed with call syntax using positional and/or keyword arguments:
-
node('attrname', 'value')sets oneattrnametovalue -
node('a1', 'v1', 'a2', 'v2')sets two attributes, etc. -
node(attr=value)sets one attribute
If the same attribute is set using both positional and keyword arguments, the positional value wins.
The final XML string can be generated from a node with unicode(node) or str(node).