jxmlease Documentation

jxmlease Documentation
Release 1.0.2dev1
Juniper Networks
April 18, 2016
Contents
1
Welcome
1.1 Installation . . . . . . . . .
1.2 Parsing XML . . . . . . . .
1.3 XMLDictNode Ojbects . .
1.4 XMLListNode Ojbects . . .
1.5 XMLCDATANode Ojbects .
1.6 Producing XML Output . .
1.7 Module Index . . . . . . . .
Python Module Index
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1
1
2
6
19
32
48
49
51
i
ii
CHAPTER 1
Welcome
jxmlease converts between XML and intelligent Python data structures.
For a quick start, you can use the parse() method to convert a block of XML to a Python data structure. This
example parses xml and uses the XMLDictNode.prettyprint() method to display the result:
>>> xml = "<a><b><c>foo</c><c>bar</c></b></a>"
>>> parse(xml).prettyprint()
{u'a': {u'b': {u'c': [u'foo', u'bar']}}}
Or, you can use the XMLDictNode class to convert a Python data structure to an intelligent XML data structure. The
following example creates an XMLDictNode object from data_structure and outputs the resulting XML using
the XMLNodeBase.emit_xml() method:
>>> data_structure = {u'a': {u'b': {u'c': [u'foo', u'bar']}}}
>>> print XMLDictNode(data_structure).emit_xml()
<?xml version="1.0" encoding="utf-8"?>
<a>
<b>
<c>foo</c>
<c>bar</c>
</b>
</a>
1.1 Installation
1.1.1 Requirements
• Python 2.6 or greater (Python 3.x is supported)
• pip the installation tool for the Python Package Index (PyPI)
1.1.2 Prerequisites
jxmlease requires an implementation of the ElementTree API. Python (beginning in version 2.5) includes an implementation in the standard library which satisfies this prerequisite.
While not a pre-requisite, jxmlease will use some of the advanced functionality provided by the lxml module, if it is
installed.
1
jxmlease Documentation, Release 1.0.2dev1
Of particular note is that lxml will maintain the original namespace identifiers when you use jxmlease to iterate over
an lxml ElementTree data structure.
The standard library’s ElementTree data structures do not maintain the original namespace identifiers. See the
“Namespace Identifiers” section of jxmlease.EtreeParser for more details on this restriction. Note: This is
only applicable when using jxmlease to parse ElementTree data structures. This is not applicable when using jxmlease
to parse text.
See lxml installation for details on installing lxml.
1.1.3 Installing the latest released version of jxmlease
Simply execute:
pip install jxmlease
1.1.4 Installing the latest development version of the jxmlease master branch
Execute:
pip install git+https://github.com/Juniper/jxmlease.git
(Note git must be installed).
1.1.5 Installing a specific version, branch, tag, etc.
Execute:
pip install git+https://github.com/Juniper/jxmlease.git@<branch,tag,commit>
(Note git must be installed).
1.1.6 Upgrading
Upgrading has the same requirements as installation. Simply add the -U (upgrade) option to the pip command:
pip install -U jxmlease
1.2 Parsing XML
class jxmlease.Parser(**kwargs)
Creates Python data structures from raw XML.
This class creates a callable object used to parse XML into Python data structures. You can provide optional
parameters at the class creation time. These parameters modify the default behavior of the parser. When you
invoke the callable object to parse a document, you can supply additional parameters to override the values
specified when the Parser object was created.
General usage is:
>>> myparser = Parser()
>>> root = myparser("<a>foo</a>")
2
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
Calling a Parser object returns an XMLDictNode containing the parsed XML tree.
In this example, root is an XMLDictNode which contains a representation of the parsed XML:
>>> isinstance(root, XMLDictNode)
True
>>> root.prettyprint()
{u'a': u'foo'}
>>> print root.emit_xml()
<?xml version="1.0" encoding="utf-8"?>
<a>foo</a>
If you will just be using a parser once, you can just use the parse() method, which is a shortcut way of
creating a Parser class and calling it all in one call. You can provide the same arguments to the parse()
method that you provide to the Parser class.
For example:
>>> root = jxmlease.parse('<a x="y"><b>1</b><b>2</b><b>3</b></a>')
>>> root.prettyprint()
{u'a': {u'b': [u'1', u'2', u'3']}}
It is possible to call a Parser object as a generator by specifying the generator parameter. The
generator parameter contains a list of paths to match. If paths are provided in this parameter, the behavior of the parser is changed. Instead of returning the root node of a parsed XML hierarchy, the parser returns
a generator object. On each call to the generator object, it will return the next node that matches one of the
provided paths.
Paths are provided in a format similar to XPath expressions. For example, /a/b will match node <b> in this
XML:
<a>
<b/>
</a>
If a path begins with a /, it must exactly match the full path to a node. If a path does not begin with a /, it must
exactly match the “right side” of the path to a node. For example, consider this XML:
<a>
<b>
<c/>
</b>
</a>
In this example, /a/b/c, c, b/c, and a/b/c all match the <c> node.
For each match, the generator returns a tuple of: (path,match_string,xml_node), where the path is
the calculated absolute path to the matching node, match_string is the user-supplied match string that triggered
the match, and xml_node is the object representing that node (an instance of a XMLNodeBase subclass).
For example:
>>> xml = '<a x="y"><b>1</b><b>2</b><b>3</b></a>'
>>> myparser = Parser(generator=["/a/b"])
>>> for (path, match, value) in myparser(xml):
...
print "%s: %s" % (path, value)
...
/a/b: 1
/a/b: 2
/a/b: 3
1.2. Parsing XML
3
jxmlease Documentation, Release 1.0.2dev1
When calling the parser, you can specify all of these parameters. When creating a parsing instance, you can
specify all of these parameters except xml_input:
Parameters
• xml_input (stirng or file-like object) – Contains the XML to parse.
• encoding (string or None) – The input’s encoding. If not provided, this defaults to
‘utf-8’.
• expat (An expat, or equivalent, parser class) – Used for parsing the
XML input. If not provided, defaults to the expat parser in xml.parsers.
• process_namespaces (bool) – If True, namespaces in tags and attributes are converted to their full URL value. If False (the default), the namespaces in tags and attributes
are left unchanged.
• namespace_separator (string) – If process_namespaces is True, this specifies the separator that expat should use between namespaces and identifiers in tags and
attributes
• xml_attribs (bool) – If True (the default), include XML attributes. If False, ignore
them.
• strip_whitespace (bool) – If True (the default), strip whitespace at the start and end
of CDATA. If False, keep all whitespace.
• namespaces (dict) – A remapping for namespaces. If supplied, identifiers with a namespace prefix will have their namespace prefix rewritten based on the dictionary. The code will
look for namespaces[current_namespace]. If found, current_namespace
will be replaced with the result of the lookup.
• strip_namespace (bool) – If True, the namespace prefix will be removed from all
identifiers. If False (the default), the namespace prefix will be retained.
• cdata_separator (string) – When encountering “semi-structured” XML (where the
XML has CDATA and tags intermixed at the same level), the cdata_separator will
be placed between the different groups of CDATA. By default, the cdata_separator
parameter is ‘’, which results in the CDATA groups being concatenated without separator.
• generator (list of strings) – A list of paths to match. If paths are provided here,
the behavior of the parser is changed. Instead of returning the root node of a parsed XML
hierarchy, the parser returns a generator object. On each call to the generator object,
it will return the next node that matches one of the provided paths.
Returns
A callable instance of the Parser class.
Calling a Parser object returns an XMLDictNode containing the parsed XML tree.
Alternatively, if the generator parameter is specified, a generator object is returned.
__call__(xml_input, **kwargs)
See class documentation.
__delattr__
x.__delattr__(‘name’) <==> del x.name
__format__()
default object formatter
__getattribute__
x.__getattribute__(‘name’) <==> x.name
4
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
__hash__
__reduce__()
helper for pickle
__reduce_ex__()
helper for pickle
__repr__
__setattr__
x.__setattr__(‘name’, value) <==> x.name = value
__sizeof__() → int
size of object in memory, in bytes
__str__
jxmlease.parse(xml_input, **kwargs)
Create Python data structures from raw XML.
See the Parser class documentation.
class jxmlease.EtreeParser(**kwargs)
Creates Python data structures from an ElementTree object.
This class returns a callable object. You can provide parameters at the class creation time. These parameters
modify the default parameters for the parser. When you call the callable object to parse a document, you can
supply additional parameters to override the default values.
General usage is like this:
>>> myparser = Parser()
>>> root = myparser(etree_root)
For detailed usage information, please see the :py:class‘Parser‘ class. Other than the differences noted below,
the behavior of the two classes should be the same. Namespace Identifiers:
In certain versions of ElementTree, the original namespace identifiers are not maintained. In these cases,
the class will recreate namespace identfiers to represent the original namespaces. It will add appropriate xmlns
attributes to maintain the original namespace mapping. However, the actual identifier will be lost. As best I can
tell, this is a bug with ElementTree, rather than this code. To avoid this problem, use lxml.
Single-invocation Parsing:
If you will just be using a parser once, you can just use the parse_etree() method, which is a shortcut way
of creating a EtreeParser class and calling it all in one call. You can provide the same arguments to the
parse_etree() method that you can provide to the EtreeParser class.
Parameters etree_root (ElementTree) – An ElementTree object representing the tree
you wish to parse.
Also accepts most of the same arguments as the Parser class. However, it does not accept the xml_input,
expat, or encoding parameters.
__call__(etree_root, **kwargs)
See the class documentation.
__delattr__
x.__delattr__(‘name’) <==> del x.name
__format__()
default object formatter
1.2. Parsing XML
5
jxmlease Documentation, Release 1.0.2dev1
__getattribute__
x.__getattribute__(‘name’) <==> x.name
__hash__
__reduce__()
helper for pickle
__reduce_ex__()
helper for pickle
__repr__
__setattr__
x.__setattr__(‘name’, value) <==> x.name = value
__sizeof__() → int
size of object in memory, in bytes
__str__
jxmlease.parse_etree(etree_root, **kwargs)
Create Python data structures from an ElementTree object.
See the EtreeParser class documentation.
1.3 XMLDictNode Ojbects
class jxmlease.XMLDictNode(*args, **kwargs)
Initialize an XMLDictNode object.
The optional first parameter can be the value to which the object should be initialized. All other parameters must
be given as keywords.
Normally, the user can simply run this as:
>>> node = XMLDictNode(initializer)
In fact, the best way to use this is:
>>> root = XMLDictNode({'root': {'branch': { 'leaf': 'a'}}})
That will set all the tags, keys, etc. correctly. However, if you really want to customize a node, there are other
parameters available. Note that these parameters only impact this node and descendants. They don’t actually
add the node to a tree. Therefore, their use is discouraged. Instead, you can probably use the add_node()
method to build your tree correctly.
The one exception to this general rule is when adding a hunk of a tree. For example, assume you currently have
this XML structure:
<a>
<b>
<node1>a</node1>
</b>
</a>
And, assume you want to add another node b to create this XML structure:
<a>
<b>
<node1>a</node1>
6
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
</b>
<b>
<node2>b</node1>
</b>
</a>
In that case, you might do something like this:
>>> root.prettyprint()
{u'a': {u'b': {u'node1': u'a'}}}
>>> new_b = {'node2': 'b'}
>>> new_b = XMLDictNode(new_b, tag="b")
>>> _ = root['a'].add_node(tag="b", new_node=new_b)
>>> root.prettyprint()
{u'a': {u'b': [{u'node1': u'a'}, {'node2': u'b'}]}}
And, you can print the XML to prove it is formatted correctly:
>>> print root.emit_xml()
<?xml version="1.0" encoding="utf-8"?>
<a>
<b>
<node1>a</node1>
</b>
<b>
<node2>b</node2>
</b>
</a>
Parameters
• initializer (as appropriate for node) – The initial value for the node.
• tag (string) – The XML tag for this node.
• key (string or tuple) – The dictionary key used for this node.
• xml_attrs (dict) – The XML attributes for the node.
• text (string) – The node’s initial CDATA value.
XMLCDATANode objects.)
(Note that this is ignored for
• parent (Instance of a sub-class of XMLNodeBase) – A reference to the object’s parent
node in the data structure.
• convert (bool) – If True, the convert() method is run on the object’s children during
object initialization.
• deep (bool) – If True (and the convert parameter is True), the convert() method is
run recursively on the object’s children during object initialization.
__cmp__
__contains__(k) → True if D has a key k, else False
__delattr__
x.__delattr__(‘name’) <==> del x.name
__format__()
default object formatter
1.3. XMLDictNode Ojbects
7
jxmlease Documentation, Release 1.0.2dev1
__ge__
x.__ge__(y) <==> x>=y
__getattribute__
x.__getattribute__(‘name’) <==> x.name
__getitem__()
x.__getitem__(y) <==> x[y]
__gt__
x.__gt__(y) <==> x>y
__le__
x.__le__(y) <==> x<=y
__len__
__lt__
x.__lt__(y) <==> x<y
__reduce_ex__()
helper for pickle
__setattr__
x.__setattr__(‘name’, value) <==> x.name = value
__sizeof__() → size of D in memory, in bytes
add_node(tag, key=None, text=u’‘, new_node=None, update=True, **kwargs)
Add an XML node to an XML tree.
This method adds a new XML node as a child of the current node. If the current node is an
XMLCDATANode, it will be converted to an XMLDictNode so that it can hold children. If the current node is an XMLDictNode and you attempt to add a node with a duplicate key, the code will create a
list to hold the existing node and add the new node to the list.
By default, all new nodes are created as XMLCDATANode objects. You can include any keyword parameters that you could provide when creating an XMLCDATANode object. If supplied, these additional
keyword parameters are passed to the XMLCDATANode.__init__() function.
Parameters
• tag (string) – The XML tag of the node.
• key (string or tuple) – The dictionary key that the method should use for the node.
If None (the default), the tag is is used as the key.
• text (string) – The CDATA for the new node. The default value is an empty string.
• new_node (instance of a subclass of XMLNodeBase) – If supplied, this will be used for
the new node instead of a new instance of the XMLCDATANode. If supplied, the text
parameter and additional keyword arguments are ignored.
• update (bool) – If True (the default), update the reverse linkages in the new node to
point to the parent. If False, only create the one-way linkages from the parent to the child.
(Note: This should always be True unless you are creating a temporary tree for some
reason. Setting this to False may create inconsistent data that causes problems later.)
Raises
• AttributeError – If the node is out of date (See get_current_node()) or the
method encounters irrecoverable data inconsistency while making changes to the XML
tree.
8
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
• TypeError – If new_node is not None and not an instance of XMLNodeBase
append_cdata(cdata, return_node=False)
Append text to a node’s CDATA.
This method appends text to a node’s CDATA. Note that any node can contain CDATA in what is called
“semi-structured” XML. However, nodes that only contain CDATA are represented as XMLCDATANode
objects. Regardless of the node, you can use this same method to append CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary; however, any local references you have saved for the node will become stale. You can obtain the updated node by setting the return_node parameter to True or by running the get_current_node()
method on the old node. For this reason, if you plan to keep a local reference to XML node in question, it
is a good idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.append_cdata("foo", True)
Parameters
• cdata (string) – The text value that should be used for the node’s CDATA.
• return_node (bool) – Whether the method should return the updated node.
Returns None, if return_node is False, otherwise, the updated node object.
Raises AttributeError – If the node is out of date. (See get_current_node().)
clear() → None. Remove all items from od.
copy() → a shallow copy of od
delete_xml_attr(attr)
Delete an XML attribute.
This method deletes an XML attribute from the node. If the attribute does not exist, it raises a KeyError.
Parameters attr (string) – The name of the XML attribute.
Returns None
Raises
• KeyError – If the attr is not found.
• AttributeError – If the node is out of date. (See get_current_node().)
dict(attrs=None, tags=None, func=None, in_place=False, promote=False)
Return a dictionary keyed as indicated by the parameters.
This method lets you re-key your data with some flexibility. It takes the current node (whether a single
node or a list) and turns it into a dictionary. If the current node is a list, all the list members are added to
the dictionary. If the current node is not a list, just the current node is added to the dictonary.
The key for each node is determined by the attrs, tags, and func parameters, in that order of precedence. For each node, the method looks for child nodes that have an XML attribute that exactly matches
one of the attributes in the attrs argument. If it finds a match, it uses the node’s (not the attribute’s)
CDATA as the key.
If the method does not find a matching attribute, it looks for child nodes that have a tag that exactly matches
one of the tags in the tags argument. If it finds a match, it uses the node’s CDATA as the key.
1.3. XMLDictNode Ojbects
9
jxmlease Documentation, Release 1.0.2dev1
If the method does not find a matching tag, it passes the node to the user-suppled function (supplied by the
func parameter) and uses the return value as the key.
If the func is not provided or returns a value that evaluates to False (e.g. None or “”), the method uses
the node’s XML tag as the key.
If there are multiple matches, the order of precedence is like this (again, this is applied for each node
independent of the other nodes):
1.The attributes in the attrs parameter, in the order they appear in the attrs parameter.
2.The tags in the tags parameter, in the order they appear in the attrs parameter.
3.The return value of the user-supplied function.
4.The node’s XML tag.
If the in_place parameter is True, then the method will replace the current node in the hierarchy with
the dictionary. Otherwise, it will create a new dictionary and return it.
If both the in_place and promote parameters are True, then the method will make the changes as
described above; however, it will add the nodes to the first dictionary it finds enclosing the curent node.
Some examples should help with this. Here is an example of the simple functionality. Note how the original
nodes are turned into a dictionary with the appropriate keys, but the original root is left untouched:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name']).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
Here is an example of a dictionary changed in place. Note how the original nodes are turned into a
dictionary with the appropriate keys and this dictionary replaces the current node in the hierarchy:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name'], in_place=True).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {'b': {u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}}}
Here is an example of the “promotion” functionality. Note how the original nodes are added directly to the
root[’a’] enclosing dictionary:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name'], in_place=True, promote=True).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}}
10
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
Quirks:
1.If the current node is the only member of a list in the XML tree, the operation will occur on that
single-node list instead of the node itself.
2.If the method encounters an exception while trying to modify the XML tree (in_place == True),
it will attempt to undo its changes; however, this logic is not completely reliable.
Parameters
• attrs (list) – The list of XML attributes that signal a node should be used as a key.
• tags (list) – The list of XML tags that signal a node should be used as a key.
• func (function) – A function that will accept a node as a parameter and return a key.
• in_place (bool) – Whether the change should be made in the XML tree.
• promote (bool) – Whether the new nodes should be added to a dictonary placed at the
current node, or they should be “promoted” to the first enclosing dictionary.
Returns An XMLDictNode. If in_place is False, the dictionary formulated from the current
node. If in_place is True, the dictionary to which the nodes were added. (Note: If
promote is True, this dictionary may contain additional entries that already existed in the
enclosing dictionary.)
Raises
• AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
• AttributeError – If in_place is True and the method encounters irrecoverable
data inconsistency while making changes to the XML tree.
emit_handler(content_handler, pretty=True, newl=’\n’, indent=’ ‘, full_document=None)
Pass the contents of the XML tree to a ContentHandler object.
This method will pass the contents of the XML tree to a ContentHandler object.
Parameters
• content_handler (ContentHandler) – The ContentHandler object to which
the XML tree wll be passed.
• pretty
(bool)
–
If
True,
this
method
will
content_handler.ignorableWhitespace() method to add
call
the
• to the output document. (whitespace) –
• newl (string) – The string which the method should use for new lines when adding
white space (see the pretty parameter).
• indent (text) – The string which the method should use for each level of indentation
when adding white space (see the pretty parameter).
• full_document
(bool)
–
If
True,
the
method
will
call
the
content_handler.startDocument()
and
content_handler.endDocument() methods at the start and end of the document, respectively. If False, it will not call these methods. If the parameter is not set, the
method will attempt to determine whether the current node is the root of an XML tree
with a single root tag. If so, it will set the full_document parameter to True; otherwise, it
will set it to False.
Returns None
1.3. XMLDictNode Ojbects
11
jxmlease Documentation, Release 1.0.2dev1
emit_xml(output=None, encoding=’utf-8’, handler=<class
**kwargs)
Return the contents of the XML tree as an XML document.
xml.sax.saxutils.XMLGenerator>,
This method will create a ContentHandler by calling the method provided by the handler parameter.
It will call emit_handler() with this ContentHandler object. In addition, this method will accept
any parameter that the emit_handler() method accepts (except the content_handler parameter).
It will pass them to the emit_handler() method when it calls it.
Parameters
• output (A file-like IO object, or None) – The file-like IO object in which
output should be placed. If None, the method will return the XML output as a string.
• encoding (string) – The encoding that should be used for the output.
• handler (function) – A method that will return a ContentHandler object. This
method will be called with two positional parameters: the output parameter (or, if None, a
file-like IO object) and the encoding parameter.
Returns If output was None, the method will return the XML output as a string. Otherwise,
None.
find_nodes_with_tag(tag, recursive=True)
Iterates over nodes that have a matching tag.
This method searches the current node and its children for nodes that have a matching tag. The tag
parameter accepts either a string value or a tuple, allowing you to search for one or more tags with a single
operation. Optionally (by providing a False value to the recursive parameter), you can limit the search
to the current node and direct children of the current node.
The method will return a generator, which you can use to iterate over the matching nodes.
For example, this will print all “name” nodes from the XML snippet that is shown:
>>> root = jxmlease.parse("""
... <?xml version="1.0" encoding="utf-8"?>
... <root>
...
<a>
...
<name>name #1</name>
...
<b>
...
<name>name #2</name>
...
</b>
...
<b>
...
<c>
...
<name>name #3</name>
...
</c>
...
</b>
...
</a>
... </root>""")
>>> print root
{u'root': {u'a': {u'b': [{u'name': u'name #2'},
{u'c': {u'name': u'name #3'}}],
u'name': u'name #1'}}}
>>> for node in root.find_nodes_with_tag('name'):
...
print node
...
name #1
name #2
name #3
However, if we turn off recursion, you will see that this returns only the direct children (if any) of the node
we select:
12
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
>>> for node in root.find_nodes_with_tag('name', recursive=False):
...
print node
...
>>> for node in root['root']['a'].find_nodes_with_tag('name', recursive=False):
...
print node
...
name #1
If you run this against an XMLDictNode without a tag (for example, the tagless root node), then the
command is run on each member of the dictionary. The impact of this is that a non-recursive search will
search for tags in the grandchildren of the tagless XMLDictNode, rather than searching the children of
the tagless XMLDictNode:
>>> root = jxmlease.parse("""
... <a>
...
<name>second-level tag</name>
...
<b>
...
<name>third-level tag</name>
...
</b>
... </a>""")
>>> for i in root.find_nodes_with_tag('name', recursive=False):
...
print i
...
second-level tag
>>> for i in root['a'].find_nodes_with_tag('name', recursive=False):
...
print i
...
second-level tag
This method never returns a list. Instead, lists pass the command through to their child nodes, which may
be returned. This ensures you get back each node you requested.
For example, here is a root node with two top-level “name” elements. Searching non-recursively for the
“name” tag returns the two “name” elements, even though they are enclosed within a dictionary and list:
>>> root = XMLDictNode()
>>> _ = root.add_node(tag='name', text='tag #1')
>>> _ = root.add_node(tag='name', text='tag #2')
>>> print root
{'name': [u'tag #1', u'tag #2']}
>>> for i in root.find_nodes_with_tag('name', recursive=False):
...
print i
...
tag #1
tag #2
>>>
Even though our examples up to this point have demonstrated text, it is worth noting that this method
returns the actual node, whatever that may be:
>>> root = jxmlease.parse("""
... <a>
...
<b>
...
<c>
...
<foo>bar</foo>
...
<status>ok</status>
...
</c>
...
</b>
... </a>""")
>>> for i in root.find_nodes_with_tag('b'):
...
print i
1.3. XMLDictNode Ojbects
13
jxmlease Documentation, Release 1.0.2dev1
...
{u'c': {u'foo': u'bar', u'status': u'ok'}}
If the recursive parameter is False, the code will check the current node. If the current node does not
match, the code will check the current node’s direct children. However, if the current node has a matching
tag and the recursive parameter is False, the code will stop its search and not check the children of the
current node.
If the recursive parameter is True (the default), the code will search the current node and all of its
children, even the children of other matching nodes. Therefore, the method may even return children of
other matches, if you specify a recursive search:
>>> root = jxmlease.parse("""
... <a>
...
<a>
...
<a>foo</a>
...
<a>bar</a>
...
</a>
... </a>""")
>>> count = 0
>>> for i in root.find_nodes_with_tag("a"):
...
count += 1
...
print("%d: %s" % (count, i))
...
1: {u'a': {u'a': [u'foo', u'bar']}}
2: {u'a': [u'foo', u'bar']}
3: foo
4: bar
>>> count = 0
>>> for i in root.find_nodes_with_tag("a", recursive=False):
...
count += 1
...
print("%d: %s" % (count, i))
...
1: {u'a': {u'a': [u'foo', u'bar']}}
You can also use a tuple as the tag parameter, in which case the method will return nodes with a tag that
matches any of the given tag values.
You can use this function to create somewhat complicated logic that mimics the functionality from XPath
“//tag” matches. For example, here we check for <xnm:warning> and <xnm:error> nodes and return their
value:
>>> root = jxmlease.parse("""
... <foo>
...
<xnm:warning>
...
<message>This is bad.</message>
...
</xnm:warning>
...
<bar>
...
<xnm:error>
...
<message>This is very bad.</message>
...
</xnm:error>
...
</bar>
... </foot>""")
>>> if root.has_node_with_tag(('xnm:warning', 'xnm:error')):
...
print "Something bad happened."
...
Something bad happened.
>>> for node in root.find_nodes_with_tag(('xnm:warning', 'xnm:error')):
...
if node.tag == 'xnm:error':
...
level = "Error:"
14
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
...
elif node.tag == 'xnm:warning':
...
level = "Warning:"
...
else:
...
level = "Unknown:"
...
print(level + " " + node.get("message", "(unknown)"))
...
Warning: This is bad.
Error: This is very bad.
Parameters
• tag (string or tuple) – The XML tag (or tags) for which to search.
• recursive (bool) – If True (the default), search recursively through all children. If
False, only search direct children.
Returns A generator which iterates over all matching nodes.
fromkeys(S[, v ]) → New ordered dictionary with keys from S.
If not specified, the value defaults to None.
get(k[, d ]) → D[k] if k in D, else d. d defaults to None.
get_cdata()
Get a node’s CDATA.
Returns A string containing the node’s CDATA.
get_current_node()
Return the current node.
There are times that the current node must be replaced in the XML tree for some reason. For example,
due to the immutability of Python strings, a new XMLCDATANode (which masquerades as a string) is
required anytime its CDATA value changes.
When this occurs, you can retrieve the latest node using the get_current_node() method. This will attempt
to find the node that succeeded the node in question. If the node is still current, it simply returns itself.
Therefore, it should always be safe to run:
>>> node = node.get_current_node()
Returns Subclass of XMLNodeBase containing the current successor to the node (if any). If
the node is still “current”, the method returns the node itself.
get_xml_attr(attr, defval=<jxmlease._basenode._NoArg object>)
Get an XML attribute.
This method returns the value of an XML attribute. If the XML attribute does not exist, it will return a
user-supplied default value. If the user did not supply a default value, it raises a KeyError.
Parameters
• attr (string) – The name of the XML attribute.
• defval (string) – The default value. (Default: Raise a KeyError.)
Returns The string value of the XML attribute, or defval.
Raises KeyError – If the attr is not found and defval is not supplied.
1.3. XMLDictNode Ojbects
15
jxmlease Documentation, Release 1.0.2dev1
get_xml_attrs()
Return the XML attribute dictionary.
This method returns the value of the XML attribute dictonary. Note that it returns the actual XML attribute
dictionary, rather than a copy. Please take caution in modifying it.
Returns The XML attribute dictionary.
Return type OrderedDict
has_key(k) → True if D has a key k, else False
has_node_with_tag(tag, recursive=True)
Determine whether a node with a matching tag exists.
This method uses the find_nodes_with_tag() method to search the current node and its children
for a node that has a matching tag. The method returns a boolean value to indicate whether at least one
matching node is found.
Because this function uses the find_nodes_with_tag() method, the parameters and algorithm are
the same as the find_nodes_with_tag() method.
Parameters
• tag (string or tuple) – The XML tag (or tags) for which to search.
• recursive (bool) – If True (the default), search recursively through all children. If
False, only search direct children.
Returns True if at least one matching node is found; otherwise, False.
has_xml_attrs()
Determine if the node has XML attributes.
Returns A bool that is True if the node has XML attributes, and False otherwise.
items() → list of (key, value) pairs in od
iteritems()
od.iteritems -> an iterator over the (key, value) pairs in od
iterkeys() → an iterator over the keys in od
itervalues()
od.itervalues -> an iterator over the values in od
jdict(in_place=False, promote=False)
Return a dictionary keyed appropriately for Junos output.
This method is a shortcut to call the dict() method with these parameters:
attrs=[('junos:key', 'junos:key', 'junos:key'),
('junos:key', 'junos:key'), 'junos:key']
tags=['name']
This will attempt to produce the correct key for each node. Some nodes have a multi-field key. If that
occurs, the dictionary key will be a tuple. In cases where there is a single key, the dictionary key will be a
string. If there is no matching node, the key will simply be the XML tag name.
Some Junos nodes use a different tag for the key. And, in some cases, the junos:key attribute is not
available. In those circumstances, you should directly call the dict() method with the correct attributes
or tags.
Please see the documentation for the dict() method for further information.
Parameters
16
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
• in_place (bool) – Whether the change should be made in the XML tree.
• promote (bool) – Whether the new nodes should be added to a dictonary placed at the
current node, or they should be “promoted” to the first enclosing dictionary.
Returns An XMLDictNode. If in_place is False, the dictionary formulated from the current
node. If in_place is True, the dictionary to which the nodes were added. (Note: If
promote is True, this dictionary may contain additional entries that already existed in the
enclosing dictionary.)
Raises
• AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
• AttributeError – If in_place is True and the method encounters irrecoverable
data inconsistency while making changes to the XML tree.
keys() → list of keys in od
list(in_place=False)
Return a node as a list.
This method returns a node as a list. This is useful when you are not sure whether a node will contain a
single entry or a list. If the node contains a list, the node itself is returned. If the node does not already
contain a list, the method creates a list, adds the node to it, and returns the list.
If the in_place parameter is True, then the change is made in the XML tree. Otherwise, the XML tree
is left unchanged and the method creates and returns a temporary list.
Parameters in_place (bool) – Whether the change should be made in the XML tree.
Returns list or XMLListNode If the current node is a list, the current node; otherwise, a list
containing the current node as its sole member.
Raises AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
pop(k[, d ]) → v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError is raised.
popitem() → (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
prettyprint(*args, **kwargs)
Print a “pretty” representation of the data structure.
This uses the pprint() method from the pprint module to print a “pretty” representation of the data
structure. The parameters are passed unchanged to the pprint() method.
The output from this method shows only the main data and not the meta data (such as XML attributes).
When using pprint(), it is necessary to use this method to get a reasonable representation of the data;
otherwise, pprint() will not know how to represent the object in a “pretty” way.
set_cdata(cdata, return_node=False)
Set a node’s CDATA.
This method sets a node’s CDATA. Note that any node can contain CDATA in what is called “semistructured” XML. However, nodes that only contain CDATA are represented as XMLCDATANode objects.
Regardless of the node, you can use this same method to set the CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary;
1.3. XMLDictNode Ojbects
17
jxmlease Documentation, Release 1.0.2dev1
however, any local references you have saved for the node will become stale. You can obtain the updated
node by setting the return_node parameter to True or by running the get_current_node() method
on the old node. For this reason, if you plan to keep a local reference to XML node in question, it is a good
idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.set_cdata("foo", True)
Parameters
• cdata (string) – The text value that should be used for the node’s CDATA.
• return_node (bool) – Whether the method should return the updated node.
Returns None or the updated node object if return_node is True.
Raises AttributeError – If the node is out of date. (See get_current_node().)
set_xml_attr(attr, val)
Set an XML attribute.
This method sets the XML attribute to the given value. If the XML attribute already existed, its value is
overridden by the new value. If the XML attribute did not already exist, it is created.
Parameters
• attr (string) – The name of the XML attribute.
• val (string) – The value of the XML attribute.
Returns None
Raises AttributeError – If the node is out of date. (See get_current_node().)
setdefault(k[, d ]) → od.get(k,d), also set od[k]=d if k not in od
standardize(deep=True)
Convert all child nodes to instances of an XMLNodeBase sub-class.
This method is useful when you have added a child node directly to a dictionary or list and now want to
convert it to the appropriate XMLNodeBase sub-class.
Parameters deep (bool) – If True (the default), recursively descend through all children, converting all nodes, as needed. If False, only convert direct children of the node.
Returns None
strip_cdata(chars=None, return_node=False)
Strip leading/trailing characters from a node’s CDATA.
This method runs the string class’ strip() method on a node’s CDATA and updates the node’s CDATA with the result.
(This is the functional equivalent to
node.set_cdata(node.get_cdata().strip()).)
Note that any node can contain CDATA in what is called “semi-structured” XML. However, nodes that
only contain CDATA are represented as XMLCDATANode objects. Regardless of the node, you can use
this same method to append CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary;
however, any local references you have saved for the node will become stale. You can obtain the updated
node by setting the return_node parameter to True or by running the get_current_node() method
on the old node. For this reason, if you plan to keep a local reference to XML node in question, it is a good
idea to run the method like this:
18
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
>>> node = root['a']['b'][0]
>>> node = node.strip_cdata(return_node=True)
Parameters
• chars (string) – Contains the characters to strip. This is passed to the string class’
strip() method.
• return_node (bool) – Whether the method should return the updated node.
Returns None if return_node is False; otherwise, the updated node object.
Raises AttributeError – If the node is out of date. (See get_current_node().)
update([E ], **F) → None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method,
does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
values() → list of values in od
viewitems() → a set-like object providing a view on od’s items
viewkeys() → a set-like object providing a view on od’s keys
viewvalues() → an object providing a view on od’s values
1.4 XMLListNode Ojbects
class jxmlease.XMLListNode(*args, **kwargs)
Initialize an XMLListNode object.
The optional first parameter can be the value to which the object should be initialized. All other parameters must
be given as keywords.
Normally, the user can simply run this as:
>>> node = XMLListNode(initializer)
In fact, the best way to use this is:
>>> root = XMLDictNode({'root': {'branch': { 'leaf': 'a'}}})
That will set all the tags, keys, etc. correctly. However, if you really want to customize a node, there are other
parameters available. Note that these parameters only impact this node and descendants. They don’t actually
add the node to a tree. Therefore, their use is discouraged. Instead, you can probably use the add_node()
method to build your tree correctly.
The one exception to this general rule is when adding a hunk of a tree. For example, assume you currently have
this XML structure:
<a>
<b>
<node1>a</node1>
</b>
</a>
And, assume you want to add another node b to create this XML structure:
1.4. XMLListNode Ojbects
19
jxmlease Documentation, Release 1.0.2dev1
<a>
<b>
<node1>a</node1>
</b>
<b>
<node2>b</node1>
</b>
</a>
In that case, you might do something like this:
>>> root.prettyprint()
{u'a': {u'b': {u'node1': u'a'}}}
>>> new_b = {'node2': 'b'}
>>> new_b = XMLDictNode(new_b, tag="b")
>>> _ = root['a'].add_node(tag="b", new_node=new_b)
>>> root.prettyprint()
{u'a': {u'b': [{u'node1': u'a'}, {'node2': u'b'}]}}
And, you can print the XML to prove it is formatted correctly:
>>> print root.emit_xml()
<?xml version="1.0" encoding="utf-8"?>
<a>
<b>
<node1>a</node1>
</b>
<b>
<node2>b</node2>
</b>
</a>
Parameters
• initializer (as appropriate for node) – The initial value for the node.
• tag (string) – The XML tag for this node.
• key (string or tuple) – The dictionary key used for this node.
• xml_attrs (dict) – The XML attributes for the node.
• text (string) – The node’s initial CDATA value.
XMLCDATANode objects.)
(Note that this is ignored for
• parent (Instance of a sub-class of XMLNodeBase) – A reference to the object’s parent
node in the data structure.
• convert (bool) – If True, the convert() method is run on the object’s children during
object initialization.
• deep (bool) – If True (and the convert parameter is True), the convert() method is
run recursively on the object’s children during object initialization.
__add__
x.__add__(y) <==> x+y
__contains__
x.__contains__(y) <==> y in x
__delattr__
x.__delattr__(‘name’) <==> del x.name
20
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
__delitem__
x.__delitem__(y) <==> del x[y]
__delslice__
x.__delslice__(i, j) <==> del x[i:j]
Use of negative indices is not supported.
__eq__
x.__eq__(y) <==> x==y
__format__()
default object formatter
__ge__
x.__ge__(y) <==> x>=y
__getattribute__
x.__getattribute__(‘name’) <==> x.name
__getitem__()
x.__getitem__(y) <==> x[y]
__getslice__
x.__getslice__(i, j) <==> x[i:j]
Use of negative indices is not supported.
__gt__
x.__gt__(y) <==> x>y
__iadd__
x.__iadd__(y) <==> x+=y
__imul__
x.__imul__(y) <==> x*=y
__iter__
__le__
x.__le__(y) <==> x<=y
__len__
__lt__
x.__lt__(y) <==> x<y
__mul__
x.__mul__(n) <==> x*n
__ne__
x.__ne__(y) <==> x!=y
__reduce__()
helper for pickle
__reduce_ex__()
helper for pickle
__reversed__()
L.__reversed__() – return a reverse iterator over the list
__rmul__
x.__rmul__(n) <==> n*x
1.4. XMLListNode Ojbects
21
jxmlease Documentation, Release 1.0.2dev1
__setattr__
x.__setattr__(‘name’, value) <==> x.name = value
__setitem__
x.__setitem__(i, y) <==> x[i]=y
__setslice__
x.__setslice__(i, j, y) <==> x[i:j]=y
Use of negative indices is not supported.
__sizeof__()
L.__sizeof__() – size of L in memory, in bytes
add_node(*args, **kwargs)
Add an XML node to the XML tree.
You should NOT call this method on an XMLListNode. Instead, call the add_node method on an
XMLCDATANode or an XMLDictNode.
Raises
• AttributeError – If the node is out of date. (See get_current_node.)
• TypeError – If called on an XMLListNode.
append()
L.append(object) – append object to end
append_cdata(cdata, return_node=False)
Append text to a node’s CDATA.
This method appends text to a node’s CDATA. Note that any node can contain CDATA in what is called
“semi-structured” XML. However, nodes that only contain CDATA are represented as XMLCDATANode
objects. Regardless of the node, you can use this same method to append CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary; however, any local references you have saved for the node will become stale. You can obtain the updated node by setting the return_node parameter to True or by running the get_current_node()
method on the old node. For this reason, if you plan to keep a local reference to XML node in question, it
is a good idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.append_cdata("foo", True)
Parameters
• cdata (string) – The text value that should be used for the node’s CDATA.
• return_node (bool) – Whether the method should return the updated node.
Returns None, if return_node is False, otherwise, the updated node object.
Raises AttributeError – If the node is out of date. (See get_current_node().)
count(value) → integer – return number of occurrences of value
delete_xml_attr(attr)
Delete an XML attribute.
This method deletes an XML attribute from the node. If the attribute does not exist, it raises a KeyError.
Parameters attr (string) – The name of the XML attribute.
22
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
Returns None
Raises
• KeyError – If the attr is not found.
• AttributeError – If the node is out of date. (See get_current_node().)
dict(attrs=None, tags=None, func=None, in_place=False, promote=False)
Return a dictionary keyed as indicated by the parameters.
This method lets you re-key your data with some flexibility. It takes the current node (whether a single
node or a list) and turns it into a dictionary. If the current node is a list, all the list members are added to
the dictionary. If the current node is not a list, just the current node is added to the dictonary.
The key for each node is determined by the attrs, tags, and func parameters, in that order of precedence. For each node, the method looks for child nodes that have an XML attribute that exactly matches
one of the attributes in the attrs argument. If it finds a match, it uses the node’s (not the attribute’s)
CDATA as the key.
If the method does not find a matching attribute, it looks for child nodes that have a tag that exactly matches
one of the tags in the tags argument. If it finds a match, it uses the node’s CDATA as the key.
If the method does not find a matching tag, it passes the node to the user-suppled function (supplied by the
func parameter) and uses the return value as the key.
If the func is not provided or returns a value that evaluates to False (e.g. None or “”), the method uses
the node’s XML tag as the key.
If there are multiple matches, the order of precedence is like this (again, this is applied for each node
independent of the other nodes):
1.The attributes in the attrs parameter, in the order they appear in the attrs parameter.
2.The tags in the tags parameter, in the order they appear in the attrs parameter.
3.The return value of the user-supplied function.
4.The node’s XML tag.
If the in_place parameter is True, then the method will replace the current node in the hierarchy with
the dictionary. Otherwise, it will create a new dictionary and return it.
If both the in_place and promote parameters are True, then the method will make the changes as
described above; however, it will add the nodes to the first dictionary it finds enclosing the curent node.
Some examples should help with this. Here is an example of the simple functionality. Note how the original
nodes are turned into a dictionary with the appropriate keys, but the original root is left untouched:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name']).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
Here is an example of a dictionary changed in place. Note how the original nodes are turned into a
dictionary with the appropriate keys and this dictionary replaces the current node in the hierarchy:
1.4. XMLListNode Ojbects
23
jxmlease Documentation, Release 1.0.2dev1
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name'], in_place=True).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {'b': {u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}}}
Here is an example of the “promotion” functionality. Note how the original nodes are added directly to the
root[’a’] enclosing dictionary:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name'], in_place=True, promote=True).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}}
Quirks:
1.If the current node is the only member of a list in the XML tree, the operation will occur on that
single-node list instead of the node itself.
2.If the method encounters an exception while trying to modify the XML tree (in_place == True),
it will attempt to undo its changes; however, this logic is not completely reliable.
Parameters
• attrs (list) – The list of XML attributes that signal a node should be used as a key.
• tags (list) – The list of XML tags that signal a node should be used as a key.
• func (function) – A function that will accept a node as a parameter and return a key.
• in_place (bool) – Whether the change should be made in the XML tree.
• promote (bool) – Whether the new nodes should be added to a dictonary placed at the
current node, or they should be “promoted” to the first enclosing dictionary.
Returns An XMLDictNode. If in_place is False, the dictionary formulated from the current
node. If in_place is True, the dictionary to which the nodes were added. (Note: If
promote is True, this dictionary may contain additional entries that already existed in the
enclosing dictionary.)
Raises
• AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
• AttributeError – If in_place is True and the method encounters irrecoverable
data inconsistency while making changes to the XML tree.
emit_handler(content_handler, pretty=True, newl=’\n’, indent=’ ‘, full_document=None)
Pass the contents of the XML tree to a ContentHandler object.
This method will pass the contents of the XML tree to a ContentHandler object.
24
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
Parameters
• content_handler (ContentHandler) – The ContentHandler object to which
the XML tree wll be passed.
• pretty
(bool)
–
If
True,
this
method
will
content_handler.ignorableWhitespace() method to add
call
the
• to the output document. (whitespace) –
• newl (string) – The string which the method should use for new lines when adding
white space (see the pretty parameter).
• indent (text) – The string which the method should use for each level of indentation
when adding white space (see the pretty parameter).
• full_document
(bool)
–
If
True,
the
method
will
call
the
content_handler.startDocument()
and
content_handler.endDocument() methods at the start and end of the document, respectively. If False, it will not call these methods. If the parameter is not set, the
method will attempt to determine whether the current node is the root of an XML tree
with a single root tag. If so, it will set the full_document parameter to True; otherwise, it
will set it to False.
Returns None
emit_xml(output=None, encoding=’utf-8’, handler=<class
**kwargs)
Return the contents of the XML tree as an XML document.
xml.sax.saxutils.XMLGenerator>,
This method will create a ContentHandler by calling the method provided by the handler parameter.
It will call emit_handler() with this ContentHandler object. In addition, this method will accept
any parameter that the emit_handler() method accepts (except the content_handler parameter).
It will pass them to the emit_handler() method when it calls it.
Parameters
• output (A file-like IO object, or None) – The file-like IO object in which
output should be placed. If None, the method will return the XML output as a string.
• encoding (string) – The encoding that should be used for the output.
• handler (function) – A method that will return a ContentHandler object. This
method will be called with two positional parameters: the output parameter (or, if None, a
file-like IO object) and the encoding parameter.
Returns If output was None, the method will return the XML output as a string. Otherwise,
None.
extend()
L.extend(iterable) – extend list by appending elements from the iterable
find_nodes_with_tag(tag, recursive=True)
Iterates over nodes that have a matching tag.
This method searches the current node and its children for nodes that have a matching tag. The tag
parameter accepts either a string value or a tuple, allowing you to search for one or more tags with a single
operation. Optionally (by providing a False value to the recursive parameter), you can limit the search
to the current node and direct children of the current node.
The method will return a generator, which you can use to iterate over the matching nodes.
For example, this will print all “name” nodes from the XML snippet that is shown:
1.4. XMLListNode Ojbects
25
jxmlease Documentation, Release 1.0.2dev1
>>> root = jxmlease.parse("""
... <?xml version="1.0" encoding="utf-8"?>
... <root>
...
<a>
...
<name>name #1</name>
...
<b>
...
<name>name #2</name>
...
</b>
...
<b>
...
<c>
...
<name>name #3</name>
...
</c>
...
</b>
...
</a>
... </root>""")
>>> print root
{u'root': {u'a': {u'b': [{u'name': u'name #2'},
{u'c': {u'name': u'name #3'}}],
u'name': u'name #1'}}}
>>> for node in root.find_nodes_with_tag('name'):
...
print node
...
name #1
name #2
name #3
However, if we turn off recursion, you will see that this returns only the direct children (if any) of the node
we select:
>>> for node in root.find_nodes_with_tag('name', recursive=False):
...
print node
...
>>> for node in root['root']['a'].find_nodes_with_tag('name', recursive=False):
...
print node
...
name #1
If you run this against an XMLDictNode without a tag (for example, the tagless root node), then the
command is run on each member of the dictionary. The impact of this is that a non-recursive search will
search for tags in the grandchildren of the tagless XMLDictNode, rather than searching the children of
the tagless XMLDictNode:
>>> root = jxmlease.parse("""
... <a>
...
<name>second-level tag</name>
...
<b>
...
<name>third-level tag</name>
...
</b>
... </a>""")
>>> for i in root.find_nodes_with_tag('name', recursive=False):
...
print i
...
second-level tag
>>> for i in root['a'].find_nodes_with_tag('name', recursive=False):
...
print i
...
second-level tag
This method never returns a list. Instead, lists pass the command through to their child nodes, which may
be returned. This ensures you get back each node you requested.
26
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
For example, here is a root node with two top-level “name” elements. Searching non-recursively for the
“name” tag returns the two “name” elements, even though they are enclosed within a dictionary and list:
>>> root = XMLDictNode()
>>> _ = root.add_node(tag='name', text='tag #1')
>>> _ = root.add_node(tag='name', text='tag #2')
>>> print root
{'name': [u'tag #1', u'tag #2']}
>>> for i in root.find_nodes_with_tag('name', recursive=False):
...
print i
...
tag #1
tag #2
>>>
Even though our examples up to this point have demonstrated text, it is worth noting that this method
returns the actual node, whatever that may be:
>>> root = jxmlease.parse("""
... <a>
...
<b>
...
<c>
...
<foo>bar</foo>
...
<status>ok</status>
...
</c>
...
</b>
... </a>""")
>>> for i in root.find_nodes_with_tag('b'):
...
print i
...
{u'c': {u'foo': u'bar', u'status': u'ok'}}
If the recursive parameter is False, the code will check the current node. If the current node does not
match, the code will check the current node’s direct children. However, if the current node has a matching
tag and the recursive parameter is False, the code will stop its search and not check the children of the
current node.
If the recursive parameter is True (the default), the code will search the current node and all of its
children, even the children of other matching nodes. Therefore, the method may even return children of
other matches, if you specify a recursive search:
>>> root = jxmlease.parse("""
... <a>
...
<a>
...
<a>foo</a>
...
<a>bar</a>
...
</a>
... </a>""")
>>> count = 0
>>> for i in root.find_nodes_with_tag("a"):
...
count += 1
...
print("%d: %s" % (count, i))
...
1: {u'a': {u'a': [u'foo', u'bar']}}
2: {u'a': [u'foo', u'bar']}
3: foo
4: bar
>>> count = 0
>>> for i in root.find_nodes_with_tag("a", recursive=False):
...
count += 1
1.4. XMLListNode Ojbects
27
jxmlease Documentation, Release 1.0.2dev1
...
print("%d: %s" % (count, i))
...
1: {u'a': {u'a': [u'foo', u'bar']}}
You can also use a tuple as the tag parameter, in which case the method will return nodes with a tag that
matches any of the given tag values.
You can use this function to create somewhat complicated logic that mimics the functionality from XPath
“//tag” matches. For example, here we check for <xnm:warning> and <xnm:error> nodes and return their
value:
>>> root = jxmlease.parse("""
... <foo>
...
<xnm:warning>
...
<message>This is bad.</message>
...
</xnm:warning>
...
<bar>
...
<xnm:error>
...
<message>This is very bad.</message>
...
</xnm:error>
...
</bar>
... </foot>""")
>>> if root.has_node_with_tag(('xnm:warning', 'xnm:error')):
...
print "Something bad happened."
...
Something bad happened.
>>> for node in root.find_nodes_with_tag(('xnm:warning', 'xnm:error')):
...
if node.tag == 'xnm:error':
...
level = "Error:"
...
elif node.tag == 'xnm:warning':
...
level = "Warning:"
...
else:
...
level = "Unknown:"
...
print(level + " " + node.get("message", "(unknown)"))
...
Warning: This is bad.
Error: This is very bad.
Parameters
• tag (string or tuple) – The XML tag (or tags) for which to search.
• recursive (bool) – If True (the default), search recursively through all children. If
False, only search direct children.
Returns A generator which iterates over all matching nodes.
get_cdata()
Get a node’s CDATA.
Returns A string containing the node’s CDATA.
get_current_node()
Return the current node.
There are times that the current node must be replaced in the XML tree for some reason. For example,
due to the immutability of Python strings, a new XMLCDATANode (which masquerades as a string) is
required anytime its CDATA value changes.
When this occurs, you can retrieve the latest node using the get_current_node() method. This will attempt
to find the node that succeeded the node in question. If the node is still current, it simply returns itself.
28
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
Therefore, it should always be safe to run:
>>> node = node.get_current_node()
Returns Subclass of XMLNodeBase containing the current successor to the node (if any). If
the node is still “current”, the method returns the node itself.
get_xml_attr(attr, defval=<jxmlease._basenode._NoArg object>)
Get an XML attribute.
This method returns the value of an XML attribute. If the XML attribute does not exist, it will return a
user-supplied default value. If the user did not supply a default value, it raises a KeyError.
Parameters
• attr (string) – The name of the XML attribute.
• defval (string) – The default value. (Default: Raise a KeyError.)
Returns The string value of the XML attribute, or defval.
Raises KeyError – If the attr is not found and defval is not supplied.
get_xml_attrs()
Return the XML attribute dictionary.
This method returns the value of the XML attribute dictonary. Note that it returns the actual XML attribute
dictionary, rather than a copy. Please take caution in modifying it.
Returns The XML attribute dictionary.
Return type OrderedDict
has_node_with_tag(tag, recursive=True)
Determine whether a node with a matching tag exists.
This method uses the find_nodes_with_tag() method to search the current node and its children
for a node that has a matching tag. The method returns a boolean value to indicate whether at least one
matching node is found.
Because this function uses the find_nodes_with_tag() method, the parameters and algorithm are
the same as the find_nodes_with_tag() method.
Parameters
• tag (string or tuple) – The XML tag (or tags) for which to search.
• recursive (bool) – If True (the default), search recursively through all children. If
False, only search direct children.
Returns True if at least one matching node is found; otherwise, False.
has_xml_attrs()
Determine if the node has XML attributes.
Returns A bool that is True if the node has XML attributes, and False otherwise.
index(value[, start[, stop ]]) → integer – return first index of value.
Raises ValueError if the value is not present.
insert()
L.insert(index, object) – insert object before index
1.4. XMLListNode Ojbects
29
jxmlease Documentation, Release 1.0.2dev1
jdict(in_place=False, promote=False)
Return a dictionary keyed appropriately for Junos output.
This method is a shortcut to call the dict() method with these parameters:
attrs=[('junos:key', 'junos:key', 'junos:key'),
('junos:key', 'junos:key'), 'junos:key']
tags=['name']
This will attempt to produce the correct key for each node. Some nodes have a multi-field key. If that
occurs, the dictionary key will be a tuple. In cases where there is a single key, the dictionary key will be a
string. If there is no matching node, the key will simply be the XML tag name.
Some Junos nodes use a different tag for the key. And, in some cases, the junos:key attribute is not
available. In those circumstances, you should directly call the dict() method with the correct attributes
or tags.
Please see the documentation for the dict() method for further information.
Parameters
• in_place (bool) – Whether the change should be made in the XML tree.
• promote (bool) – Whether the new nodes should be added to a dictonary placed at the
current node, or they should be “promoted” to the first enclosing dictionary.
Returns An XMLDictNode. If in_place is False, the dictionary formulated from the current
node. If in_place is True, the dictionary to which the nodes were added. (Note: If
promote is True, this dictionary may contain additional entries that already existed in the
enclosing dictionary.)
Raises
• AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
• AttributeError – If in_place is True and the method encounters irrecoverable
data inconsistency while making changes to the XML tree.
list(in_place=False)
Return a node as a list.
This method returns a node as a list. This is useful when you are not sure whether a node will contain a
single entry or a list. If the node contains a list, the node itself is returned. If the node does not already
contain a list, the method creates a list, adds the node to it, and returns the list.
If the in_place parameter is True, then the change is made in the XML tree. Otherwise, the XML tree
is left unchanged and the method creates and returns a temporary list.
Parameters in_place (bool) – Whether the change should be made in the XML tree.
Returns list or XMLListNode If the current node is a list, the current node; otherwise, a list
containing the current node as its sole member.
Raises AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
pop([index ]) → item – remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
prettyprint(*args, **kwargs)
Print a “pretty” representation of the data structure.
30
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
This uses the pprint() method from the pprint module to print a “pretty” representation of the data
structure. The parameters are passed unchanged to the pprint() method.
The output from this method shows only the main data and not the meta data (such as XML attributes).
When using pprint(), it is necessary to use this method to get a reasonable representation of the data;
otherwise, pprint() will not know how to represent the object in a “pretty” way.
remove()
L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.
reverse()
L.reverse() – reverse IN PLACE
set_cdata(cdata, return_node=False)
Set a node’s CDATA.
This method sets a node’s CDATA. Note that any node can contain CDATA in what is called “semistructured” XML. However, nodes that only contain CDATA are represented as XMLCDATANode objects.
Regardless of the node, you can use this same method to set the CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary;
however, any local references you have saved for the node will become stale. You can obtain the updated
node by setting the return_node parameter to True or by running the get_current_node() method
on the old node. For this reason, if you plan to keep a local reference to XML node in question, it is a good
idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.set_cdata("foo", True)
Parameters
• cdata (string) – The text value that should be used for the node’s CDATA.
• return_node (bool) – Whether the method should return the updated node.
Returns None or the updated node object if return_node is True.
Raises AttributeError – If the node is out of date. (See get_current_node().)
set_xml_attr(attr, val)
Set an XML attribute.
This method sets the XML attribute to the given value. If the XML attribute already existed, its value is
overridden by the new value. If the XML attribute did not already exist, it is created.
Parameters
• attr (string) – The name of the XML attribute.
• val (string) – The value of the XML attribute.
Returns None
Raises AttributeError – If the node is out of date. (See get_current_node().)
sort()
L.sort(cmp=None, key=None, reverse=False) – stable sort IN PLACE; cmp(x, y) -> -1, 0, 1
standardize(deep=True)
Convert all child nodes to instances of an XMLNodeBase sub-class.
1.4. XMLListNode Ojbects
31
jxmlease Documentation, Release 1.0.2dev1
This method is useful when you have added a child node directly to a dictionary or list and now want to
convert it to the appropriate XMLNodeBase sub-class.
Parameters deep (bool) – If True (the default), recursively descend through all children, converting all nodes, as needed. If False, only convert direct children of the node.
Returns None
strip_cdata(chars=None, return_node=False)
Strip leading/trailing characters from a node’s CDATA.
This method runs the string class’ strip() method on a node’s CDATA and updates the node’s CDATA with the result.
(This is the functional equivalent to
node.set_cdata(node.get_cdata().strip()).)
Note that any node can contain CDATA in what is called “semi-structured” XML. However, nodes that
only contain CDATA are represented as XMLCDATANode objects. Regardless of the node, you can use
this same method to append CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary;
however, any local references you have saved for the node will become stale. You can obtain the updated
node by setting the return_node parameter to True or by running the get_current_node() method
on the old node. For this reason, if you plan to keep a local reference to XML node in question, it is a good
idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.strip_cdata(return_node=True)
Parameters
• chars (string) – Contains the characters to strip. This is passed to the string class’
strip() method.
• return_node (bool) – Whether the method should return the updated node.
Returns None if return_node is False; otherwise, the updated node object.
Raises AttributeError – If the node is out of date. (See get_current_node().)
1.5 XMLCDATANode Ojbects
class jxmlease.XMLCDATANode(*args, **kwargs)
Initialize an XMLCDATANode object.
The optional first parameter can be the value to which the object should be initialized. All other parameters must
be given as keywords.
Normally, the user can simply run this as:
>>> node = XMLCDATANode(initializer)
In fact, the best way to use this is:
>>> root = XMLDictNode({'root': {'branch': { 'leaf': 'a'}}})
That will set all the tags, keys, etc. correctly. However, if you really want to customize a node, there are other
parameters available. Note that these parameters only impact this node and descendants. They don’t actually
add the node to a tree. Therefore, their use is discouraged. Instead, you can probably use the add_node()
method to build your tree correctly.
32
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
The one exception to this general rule is when adding a hunk of a tree. For example, assume you currently have
this XML structure:
<a>
<b>
<node1>a</node1>
</b>
</a>
And, assume you want to add another node b to create this XML structure:
<a>
<b>
<node1>a</node1>
</b>
<b>
<node2>b</node1>
</b>
</a>
In that case, you might do something like this:
>>> root.prettyprint()
{u'a': {u'b': {u'node1': u'a'}}}
>>> new_b = {'node2': 'b'}
>>> new_b = XMLDictNode(new_b, tag="b")
>>> _ = root['a'].add_node(tag="b", new_node=new_b)
>>> root.prettyprint()
{u'a': {u'b': [{u'node1': u'a'}, {'node2': u'b'}]}}
And, you can print the XML to prove it is formatted correctly:
>>> print root.emit_xml()
<?xml version="1.0" encoding="utf-8"?>
<a>
<b>
<node1>a</node1>
</b>
<b>
<node2>b</node2>
</b>
</a>
Parameters
• initializer (as appropriate for node) – The initial value for the node.
• tag (string) – The XML tag for this node.
• key (string or tuple) – The dictionary key used for this node.
• xml_attrs (dict) – The XML attributes for the node.
• text (string) – The node’s initial CDATA value.
XMLCDATANode objects.)
(Note that this is ignored for
• parent (Instance of a sub-class of XMLNodeBase) – A reference to the object’s parent
node in the data structure.
• convert (bool) – If True, the convert() method is run on the object’s children during
object initialization.
1.5. XMLCDATANode Ojbects
33
jxmlease Documentation, Release 1.0.2dev1
• deep (bool) – If True (and the convert parameter is True), the convert() method is
run recursively on the object’s children during object initialization.
__add__
x.__add__(y) <==> x+y
__contains__
x.__contains__(y) <==> y in x
__delattr__
x.__delattr__(‘name’) <==> del x.name
__eq__
x.__eq__(y) <==> x==y
__format__(format_spec) → unicode
Return a formatted version of S as described by format_spec.
__ge__
x.__ge__(y) <==> x>=y
__getattribute__
x.__getattribute__(‘name’) <==> x.name
__getitem__
x.__getitem__(y) <==> x[y]
__getslice__
x.__getslice__(i, j) <==> x[i:j]
Use of negative indices is not supported.
__gt__
x.__gt__(y) <==> x>y
__hash__
__le__
x.__le__(y) <==> x<=y
__len__
__lt__
x.__lt__(y) <==> x<y
__mod__
x.__mod__(y) <==> x%y
__mul__
x.__mul__(n) <==> x*n
__ne__
x.__ne__(y) <==> x!=y
__reduce__()
helper for pickle
__reduce_ex__()
helper for pickle
__rmod__
x.__rmod__(y) <==> y%x
34
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
__rmul__
x.__rmul__(n) <==> n*x
__setattr__
x.__setattr__(‘name’, value) <==> x.name = value
__sizeof__() → size of S in memory, in bytes
add_node(tag, key=None, *args, **kwargs)
Add an XML node to an XML tree.
This method adds a new XML node as a child of the current node. If the current node is an
XMLCDATANode, it will be converted to an XMLDictNode so that it can hold children. If the current node is an XMLDictNode and you attempt to add a node with a duplicate key, the code will create a
list to hold the existing node and add the new node to the list.
By default, all new nodes are created as XMLCDATANode objects. You can include any keyword parameters that you could provide when creating an XMLCDATANode object. If supplied, these additional
keyword parameters are passed to the XMLCDATANode.__init__() function.
Parameters
• tag (string) – The XML tag of the node.
• key (string or tuple) – The dictionary key that the method should use for the node.
If None (the default), the tag is is used as the key.
• text (string) – The CDATA for the new node. The default value is an empty string.
• new_node (instance of a subclass of XMLNodeBase) – If supplied, this will be used for
the new node instead of a new instance of the XMLCDATANode. If supplied, the text
parameter and additional keyword arguments are ignored.
• update (bool) – If True (the default), update the reverse linkages in the new node to
point to the parent. If False, only create the one-way linkages from the parent to the child.
(Note: This should always be True unless you are creating a temporary tree for some
reason. Setting this to False may create inconsistent data that causes problems later.)
Raises
• AttributeError – If the node is out of date (See get_current_node()) or the
method encounters irrecoverable data inconsistency while making changes to the XML
tree.
• TypeError – If new_node is not None and not an instance of XMLNodeBase
append_cdata(cdata, return_node=False)
Append text to a node’s CDATA.
This method appends text to a node’s CDATA. Note that any node can contain CDATA in what is called
“semi-structured” XML. However, nodes that only contain CDATA are represented as XMLCDATANode
objects. Regardless of the node, you can use this same method to append CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary; however, any local references you have saved for the node will become stale. You can obtain the updated node by setting the return_node parameter to True or by running the get_current_node()
method on the old node. For this reason, if you plan to keep a local reference to XML node in question, it
is a good idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.append_cdata("foo", True)
1.5. XMLCDATANode Ojbects
35
jxmlease Documentation, Release 1.0.2dev1
Parameters
• cdata (string) – The text value that should be used for the node’s CDATA.
• return_node (bool) – Whether the method should return the updated node.
Returns None, if return_node is False, otherwise, the updated node object.
Raises AttributeError – If the node is out of date. (See get_current_node().)
capitalize() → unicode
Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case.
center(width[, fillchar ]) → unicode
Return S centered in a Unicode string of length width. Padding is done using the specified fill character
(default is a space)
count(sub[, start[, end ]]) → int
Return the number of non-overlapping occurrences of substring sub in Unicode string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
decode([encoding[, errors ]]) → string or unicode
Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may
be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a
UnicodeDecodeError. Other possible values are ‘ignore’ and ‘replace’ as well as any other name registered
with codecs.register_error that is able to handle UnicodeDecodeErrors.
delete_xml_attr(attr)
Delete an XML attribute.
This method deletes an XML attribute from the node. If the attribute does not exist, it raises a KeyError.
Parameters attr (string) – The name of the XML attribute.
Returns None
Raises
• KeyError – If the attr is not found.
• AttributeError – If the node is out of date. (See get_current_node().)
dict(attrs=None, tags=None, func=None, in_place=False, promote=False)
Return a dictionary keyed as indicated by the parameters.
This method lets you re-key your data with some flexibility. It takes the current node (whether a single
node or a list) and turns it into a dictionary. If the current node is a list, all the list members are added to
the dictionary. If the current node is not a list, just the current node is added to the dictonary.
The key for each node is determined by the attrs, tags, and func parameters, in that order of precedence. For each node, the method looks for child nodes that have an XML attribute that exactly matches
one of the attributes in the attrs argument. If it finds a match, it uses the node’s (not the attribute’s)
CDATA as the key.
If the method does not find a matching attribute, it looks for child nodes that have a tag that exactly matches
one of the tags in the tags argument. If it finds a match, it uses the node’s CDATA as the key.
If the method does not find a matching tag, it passes the node to the user-suppled function (supplied by the
func parameter) and uses the return value as the key.
If the func is not provided or returns a value that evaluates to False (e.g. None or “”), the method uses
the node’s XML tag as the key.
36
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
If there are multiple matches, the order of precedence is like this (again, this is applied for each node
independent of the other nodes):
1.The attributes in the attrs parameter, in the order they appear in the attrs parameter.
2.The tags in the tags parameter, in the order they appear in the attrs parameter.
3.The return value of the user-supplied function.
4.The node’s XML tag.
If the in_place parameter is True, then the method will replace the current node in the hierarchy with
the dictionary. Otherwise, it will create a new dictionary and return it.
If both the in_place and promote parameters are True, then the method will make the changes as
described above; however, it will add the nodes to the first dictionary it finds enclosing the curent node.
Some examples should help with this. Here is an example of the simple functionality. Note how the original
nodes are turned into a dictionary with the appropriate keys, but the original root is left untouched:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name']).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
Here is an example of a dictionary changed in place. Note how the original nodes are turned into a
dictionary with the appropriate keys and this dictionary replaces the current node in the hierarchy:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name'], in_place=True).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {'b': {u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}}}
Here is an example of the “promotion” functionality. Note how the original nodes are added directly to the
root[’a’] enclosing dictionary:
>>> root.prettyprint()
{'a': {'b': [{'name': u'foo', 'value': u'1'},
{'name': u'bar', 'value': u'2'}]}}
>>> root['a']['b'].dict(tags=['name'], in_place=True, promote=True).prettyprint()
{u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}
>>> root.prettyprint()
{'a': {u'bar': {'name': u'bar', 'value': u'2'},
u'foo': {'name': u'foo', 'value': u'1'}}}
Quirks:
1.If the current node is the only member of a list in the XML tree, the operation will occur on that
single-node list instead of the node itself.
1.5. XMLCDATANode Ojbects
37
jxmlease Documentation, Release 1.0.2dev1
2.If the method encounters an exception while trying to modify the XML tree (in_place == True),
it will attempt to undo its changes; however, this logic is not completely reliable.
Parameters
• attrs (list) – The list of XML attributes that signal a node should be used as a key.
• tags (list) – The list of XML tags that signal a node should be used as a key.
• func (function) – A function that will accept a node as a parameter and return a key.
• in_place (bool) – Whether the change should be made in the XML tree.
• promote (bool) – Whether the new nodes should be added to a dictonary placed at the
current node, or they should be “promoted” to the first enclosing dictionary.
Returns An XMLDictNode. If in_place is False, the dictionary formulated from the current
node. If in_place is True, the dictionary to which the nodes were added. (Note: If
promote is True, this dictionary may contain additional entries that already existed in the
enclosing dictionary.)
Raises
• AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
• AttributeError – If in_place is True and the method encounters irrecoverable
data inconsistency while making changes to the XML tree.
emit_handler(content_handler, pretty=True, newl=’\n’, indent=’ ‘, full_document=None)
Pass the contents of the XML tree to a ContentHandler object.
This method will pass the contents of the XML tree to a ContentHandler object.
Parameters
• content_handler (ContentHandler) – The ContentHandler object to which
the XML tree wll be passed.
• pretty
(bool)
–
If
True,
this
method
will
content_handler.ignorableWhitespace() method to add
call
the
• to the output document. (whitespace) –
• newl (string) – The string which the method should use for new lines when adding
white space (see the pretty parameter).
• indent (text) – The string which the method should use for each level of indentation
when adding white space (see the pretty parameter).
• full_document
(bool)
–
If
True,
the
method
will
call
the
content_handler.startDocument()
and
content_handler.endDocument() methods at the start and end of the document, respectively. If False, it will not call these methods. If the parameter is not set, the
method will attempt to determine whether the current node is the root of an XML tree
with a single root tag. If so, it will set the full_document parameter to True; otherwise, it
will set it to False.
Returns None
emit_xml(output=None, encoding=’utf-8’, handler=<class
**kwargs)
Return the contents of the XML tree as an XML document.
38
xml.sax.saxutils.XMLGenerator>,
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
This method will create a ContentHandler by calling the method provided by the handler parameter.
It will call emit_handler() with this ContentHandler object. In addition, this method will accept
any parameter that the emit_handler() method accepts (except the content_handler parameter).
It will pass them to the emit_handler() method when it calls it.
Parameters
• output (A file-like IO object, or None) – The file-like IO object in which
output should be placed. If None, the method will return the XML output as a string.
• encoding (string) – The encoding that should be used for the output.
• handler (function) – A method that will return a ContentHandler object. This
method will be called with two positional parameters: the output parameter (or, if None, a
file-like IO object) and the encoding parameter.
Returns If output was None, the method will return the XML output as a string. Otherwise,
None.
encode([encoding[, errors ]]) → string or unicode
Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may
be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a
UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any
other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
endswith(suffix[, start[, end ]]) → bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at
that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to
try.
expandtabs([tabsize ]) → unicode
Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of
8 characters is assumed.
find(sub[, start[, end ]]) → int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
find_nodes_with_tag(tag, recursive=True)
Iterates over nodes that have a matching tag.
This method searches the current node and its children for nodes that have a matching tag. The tag
parameter accepts either a string value or a tuple, allowing you to search for one or more tags with a single
operation. Optionally (by providing a False value to the recursive parameter), you can limit the search
to the current node and direct children of the current node.
The method will return a generator, which you can use to iterate over the matching nodes.
For example, this will print all “name” nodes from the XML snippet that is shown:
>>> root = jxmlease.parse("""
... <?xml version="1.0" encoding="utf-8"?>
... <root>
...
<a>
...
<name>name #1</name>
...
<b>
...
<name>name #2</name>
...
</b>
...
<b>
...
<c>
...
<name>name #3</name>
1.5. XMLCDATANode Ojbects
39
jxmlease Documentation, Release 1.0.2dev1
...
</c>
...
</b>
...
</a>
... </root>""")
>>> print root
{u'root': {u'a': {u'b': [{u'name': u'name #2'},
{u'c': {u'name': u'name #3'}}],
u'name': u'name #1'}}}
>>> for node in root.find_nodes_with_tag('name'):
...
print node
...
name #1
name #2
name #3
However, if we turn off recursion, you will see that this returns only the direct children (if any) of the node
we select:
>>> for node in root.find_nodes_with_tag('name', recursive=False):
...
print node
...
>>> for node in root['root']['a'].find_nodes_with_tag('name', recursive=False):
...
print node
...
name #1
If you run this against an XMLDictNode without a tag (for example, the tagless root node), then the
command is run on each member of the dictionary. The impact of this is that a non-recursive search will
search for tags in the grandchildren of the tagless XMLDictNode, rather than searching the children of
the tagless XMLDictNode:
>>> root = jxmlease.parse("""
... <a>
...
<name>second-level tag</name>
...
<b>
...
<name>third-level tag</name>
...
</b>
... </a>""")
>>> for i in root.find_nodes_with_tag('name', recursive=False):
...
print i
...
second-level tag
>>> for i in root['a'].find_nodes_with_tag('name', recursive=False):
...
print i
...
second-level tag
This method never returns a list. Instead, lists pass the command through to their child nodes, which may
be returned. This ensures you get back each node you requested.
For example, here is a root node with two top-level “name” elements. Searching non-recursively for the
“name” tag returns the two “name” elements, even though they are enclosed within a dictionary and list:
>>> root = XMLDictNode()
>>> _ = root.add_node(tag='name', text='tag #1')
>>> _ = root.add_node(tag='name', text='tag #2')
>>> print root
{'name': [u'tag #1', u'tag #2']}
>>> for i in root.find_nodes_with_tag('name', recursive=False):
...
print i
40
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
...
tag #1
tag #2
>>>
Even though our examples up to this point have demonstrated text, it is worth noting that this method
returns the actual node, whatever that may be:
>>> root = jxmlease.parse("""
... <a>
...
<b>
...
<c>
...
<foo>bar</foo>
...
<status>ok</status>
...
</c>
...
</b>
... </a>""")
>>> for i in root.find_nodes_with_tag('b'):
...
print i
...
{u'c': {u'foo': u'bar', u'status': u'ok'}}
If the recursive parameter is False, the code will check the current node. If the current node does not
match, the code will check the current node’s direct children. However, if the current node has a matching
tag and the recursive parameter is False, the code will stop its search and not check the children of the
current node.
If the recursive parameter is True (the default), the code will search the current node and all of its
children, even the children of other matching nodes. Therefore, the method may even return children of
other matches, if you specify a recursive search:
>>> root = jxmlease.parse("""
... <a>
...
<a>
...
<a>foo</a>
...
<a>bar</a>
...
</a>
... </a>""")
>>> count = 0
>>> for i in root.find_nodes_with_tag("a"):
...
count += 1
...
print("%d: %s" % (count, i))
...
1: {u'a': {u'a': [u'foo', u'bar']}}
2: {u'a': [u'foo', u'bar']}
3: foo
4: bar
>>> count = 0
>>> for i in root.find_nodes_with_tag("a", recursive=False):
...
count += 1
...
print("%d: %s" % (count, i))
...
1: {u'a': {u'a': [u'foo', u'bar']}}
You can also use a tuple as the tag parameter, in which case the method will return nodes with a tag that
matches any of the given tag values.
You can use this function to create somewhat complicated logic that mimics the functionality from XPath
“//tag” matches. For example, here we check for <xnm:warning> and <xnm:error> nodes and return their
value:
1.5. XMLCDATANode Ojbects
41
jxmlease Documentation, Release 1.0.2dev1
>>> root = jxmlease.parse("""
... <foo>
...
<xnm:warning>
...
<message>This is bad.</message>
...
</xnm:warning>
...
<bar>
...
<xnm:error>
...
<message>This is very bad.</message>
...
</xnm:error>
...
</bar>
... </foot>""")
>>> if root.has_node_with_tag(('xnm:warning', 'xnm:error')):
...
print "Something bad happened."
...
Something bad happened.
>>> for node in root.find_nodes_with_tag(('xnm:warning', 'xnm:error')):
...
if node.tag == 'xnm:error':
...
level = "Error:"
...
elif node.tag == 'xnm:warning':
...
level = "Warning:"
...
else:
...
level = "Unknown:"
...
print(level + " " + node.get("message", "(unknown)"))
...
Warning: This is bad.
Error: This is very bad.
Parameters
• tag (string or tuple) – The XML tag (or tags) for which to search.
• recursive (bool) – If True (the default), search recursively through all children. If
False, only search direct children.
Returns A generator which iterates over all matching nodes.
format(*args, **kwargs) → unicode
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified
by braces (‘{‘ and ‘}’).
get_cdata()
Get a node’s CDATA.
Returns A string containing the node’s CDATA.
get_current_node()
Return the current node.
There are times that the current node must be replaced in the XML tree for some reason. For example,
due to the immutability of Python strings, a new XMLCDATANode (which masquerades as a string) is
required anytime its CDATA value changes.
When this occurs, you can retrieve the latest node using the get_current_node() method. This will attempt
to find the node that succeeded the node in question. If the node is still current, it simply returns itself.
Therefore, it should always be safe to run:
>>> node = node.get_current_node()
Returns Subclass of XMLNodeBase containing the current successor to the node (if any). If
the node is still “current”, the method returns the node itself.
42
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
get_xml_attr(attr, defval=<jxmlease._basenode._NoArg object>)
Get an XML attribute.
This method returns the value of an XML attribute. If the XML attribute does not exist, it will return a
user-supplied default value. If the user did not supply a default value, it raises a KeyError.
Parameters
• attr (string) – The name of the XML attribute.
• defval (string) – The default value. (Default: Raise a KeyError.)
Returns The string value of the XML attribute, or defval.
Raises KeyError – If the attr is not found and defval is not supplied.
get_xml_attrs()
Return the XML attribute dictionary.
This method returns the value of the XML attribute dictonary. Note that it returns the actual XML attribute
dictionary, rather than a copy. Please take caution in modifying it.
Returns The XML attribute dictionary.
Return type OrderedDict
has_node_with_tag(tag, recursive=True)
Determine whether a node with a matching tag exists.
This method uses the find_nodes_with_tag() method to search the current node and its children
for a node that has a matching tag. The method returns a boolean value to indicate whether at least one
matching node is found.
Because this function uses the find_nodes_with_tag() method, the parameters and algorithm are
the same as the find_nodes_with_tag() method.
Parameters
• tag (string or tuple) – The XML tag (or tags) for which to search.
• recursive (bool) – If True (the default), search recursively through all children. If
False, only search direct children.
Returns True if at least one matching node is found; otherwise, False.
has_xml_attrs()
Determine if the node has XML attributes.
Returns A bool that is True if the node has XML attributes, and False otherwise.
index(sub[, start[, end ]]) → int
Like S.find() but raise ValueError when the substring is not found.
isalnum() → bool
Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
isalpha() → bool
Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.
isdecimal() → bool
Return True if there are only decimal characters in S, False otherwise.
isdigit() → bool
Return True if all characters in S are digits and there is at least one character in S, False otherwise.
1.5. XMLCDATANode Ojbects
43
jxmlease Documentation, Release 1.0.2dev1
islower() → bool
Return True if all cased characters in S are lowercase and there is at least one cased character in S, False
otherwise.
isnumeric() → bool
Return True if there are only numeric characters in S, False otherwise.
isspace() → bool
Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.
istitle() → bool
Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase
characters may only follow uncased characters and lowercase characters only cased ones. Return False
otherwise.
isupper() → bool
Return True if all cased characters in S are uppercase and there is at least one cased character in S, False
otherwise.
jdict(in_place=False, promote=False)
Return a dictionary keyed appropriately for Junos output.
This method is a shortcut to call the dict() method with these parameters:
attrs=[('junos:key', 'junos:key', 'junos:key'),
('junos:key', 'junos:key'), 'junos:key']
tags=['name']
This will attempt to produce the correct key for each node. Some nodes have a multi-field key. If that
occurs, the dictionary key will be a tuple. In cases where there is a single key, the dictionary key will be a
string. If there is no matching node, the key will simply be the XML tag name.
Some Junos nodes use a different tag for the key. And, in some cases, the junos:key attribute is not
available. In those circumstances, you should directly call the dict() method with the correct attributes
or tags.
Please see the documentation for the dict() method for further information.
Parameters
• in_place (bool) – Whether the change should be made in the XML tree.
• promote (bool) – Whether the new nodes should be added to a dictonary placed at the
current node, or they should be “promoted” to the first enclosing dictionary.
Returns An XMLDictNode. If in_place is False, the dictionary formulated from the current
node. If in_place is True, the dictionary to which the nodes were added. (Note: If
promote is True, this dictionary may contain additional entries that already existed in the
enclosing dictionary.)
Raises
• AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
• AttributeError – If in_place is True and the method encounters irrecoverable
data inconsistency while making changes to the XML tree.
join(iterable) → unicode
Return a string which is the concatenation of the strings in the iterable. The separator between elements is
S.
44
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
list(in_place=False)
Return a node as a list.
This method returns a node as a list. This is useful when you are not sure whether a node will contain a
single entry or a list. If the node contains a list, the node itself is returned. If the node does not already
contain a list, the method creates a list, adds the node to it, and returns the list.
If the in_place parameter is True, then the change is made in the XML tree. Otherwise, the XML tree
is left unchanged and the method creates and returns a temporary list.
Parameters in_place (bool) – Whether the change should be made in the XML tree.
Returns list or XMLListNode If the current node is a list, the current node; otherwise, a list
containing the current node as its sole member.
Raises AttributeError – If the node is out of date and in_place is True.
get_current_node().)
(See
ljust(width[, fillchar ]) → int
Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character
(default is a space).
lower() → unicode
Return a copy of the string S converted to lowercase.
lstrip([chars ]) → unicode
Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove
characters in chars instead. If chars is a str, it will be converted to unicode before stripping
partition(sep) -> (head, sep, tail)
Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If
the separator is not found, return S and two empty strings.
prettyprint(*args, **kwargs)
Print a “pretty” representation of the data structure.
This uses the pprint() method from the pprint module to print a “pretty” representation of the data
structure. The parameters are passed unchanged to the pprint() method.
The output from this method shows only the main data and not the meta data (such as XML attributes).
When using pprint(), it is necessary to use this method to get a reasonable representation of the data;
otherwise, pprint() will not know how to represent the object in a “pretty” way.
replace(old, new[, count ]) → unicode
Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count
is given, only the first count occurrences are replaced.
rfind(sub[, start[, end ]]) → int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
rindex(sub[, start[, end ]]) → int
Like S.rfind() but raise ValueError when the substring is not found.
rjust(width[, fillchar ]) → unicode
Return S right-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).
1.5. XMLCDATANode Ojbects
45
jxmlease Documentation, Release 1.0.2dev1
rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself,
and the part after it. If the separator is not found, return two empty strings and S.
rsplit([sep[, maxsplit ]]) → list of strings
Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace
string is a separator.
rstrip([chars ]) → unicode
Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove
characters in chars instead. If chars is a str, it will be converted to unicode before stripping
set_cdata(cdata, return_node=False)
Set a node’s CDATA.
This method sets a node’s CDATA. Note that any node can contain CDATA in what is called “semistructured” XML. However, nodes that only contain CDATA are represented as XMLCDATANode objects.
Regardless of the node, you can use this same method to set the CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary;
however, any local references you have saved for the node will become stale. You can obtain the updated
node by setting the return_node parameter to True or by running the get_current_node() method
on the old node. For this reason, if you plan to keep a local reference to XML node in question, it is a good
idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.set_cdata("foo", True)
Parameters
• cdata (string) – The text value that should be used for the node’s CDATA.
• return_node (bool) – Whether the method should return the updated node.
Returns None or the updated node object if return_node is True.
Raises AttributeError – If the node is out of date. (See get_current_node().)
set_xml_attr(attr, val)
Set an XML attribute.
This method sets the XML attribute to the given value. If the XML attribute already existed, its value is
overridden by the new value. If the XML attribute did not already exist, it is created.
Parameters
• attr (string) – The name of the XML attribute.
• val (string) – The value of the XML attribute.
Returns None
Raises AttributeError – If the node is out of date. (See get_current_node().)
split([sep[, maxsplit ]]) → list of strings
Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings
are removed from the result.
46
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
splitlines(keepends=False) → list of strings
Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list
unless keepends is given and true.
standardize(deep=True)
Convert all child nodes to instances of an XMLNodeBase sub-class.
This method is useful when you have added a child node directly to a dictionary or list and now want to
convert it to the appropriate XMLNodeBase sub-class.
Parameters deep (bool) – If True (the default), recursively descend through all children, converting all nodes, as needed. If False, only convert direct children of the node.
Returns None
startswith(prefix[, start[, end ]]) → bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at
that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to
try.
strip([chars ]) → unicode
Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None,
remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping
strip_cdata(chars=None, return_node=False)
Strip leading/trailing characters from a node’s CDATA.
This method runs the string class’ strip() method on a node’s CDATA and updates the node’s CDATA with the result.
(This is the functional equivalent to
node.set_cdata(node.get_cdata().strip()).)
Note that any node can contain CDATA in what is called “semi-structured” XML. However, nodes that
only contain CDATA are represented as XMLCDATANode objects. Regardless of the node, you can use
this same method to append CDATA.
Note: When running this on an XMLCDATANode, the actual node will be replaced with a new node in the
tree. (This is a result of Python’s string immutability.) The function will update the XML tree, if necessary;
however, any local references you have saved for the node will become stale. You can obtain the updated
node by setting the return_node parameter to True or by running the get_current_node() method
on the old node. For this reason, if you plan to keep a local reference to XML node in question, it is a good
idea to run the method like this:
>>> node = root['a']['b'][0]
>>> node = node.strip_cdata(return_node=True)
Parameters
• chars (string) – Contains the characters to strip. This is passed to the string class’
strip() method.
• return_node (bool) – Whether the method should return the updated node.
Returns None if return_node is False; otherwise, the updated node object.
Raises AttributeError – If the node is out of date. (See get_current_node().)
swapcase() → unicode
Return a copy of S with uppercase characters converted to lowercase and vice versa.
title() → unicode
Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters
have lower case.
1.5. XMLCDATANode Ojbects
47
jxmlease Documentation, Release 1.0.2dev1
translate(table) → unicode
Return a copy of the string S, where all characters have been mapped through the given translation table,
which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped
characters are left untouched. Characters mapped to None are deleted.
upper() → unicode
Return a copy of S converted to uppercase.
zfill(width) → unicode
Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never
truncated.
1.6 Producing XML Output
You can create XML output using the emit_xml method of one of the XML node classes to produce XML output
from the node’s data. You can also use the package’s emit_xml() function to directly convert a Python object to
XML output.
1.6.1 Producing XML Output from an XML Node Object
You can produce XML output from an XMLDictNode, XMLListNode, or XMLCDATNode instance. You use the
emit_xml class method to produce the output.
XMLNodeBase.emit_xml(output=None,
encoding=’utf-8’,
xml.sax.saxutils.XMLGenerator>, **kwargs)
Return the contents of the XML tree as an XML document.
handler=<class
This method will create a ContentHandler by calling the method provided by the handler parameter. It
will call emit_handler() with this ContentHandler object. In addition, this method will accept any
parameter that the emit_handler() method accepts (except the content_handler parameter). It will
pass them to the emit_handler() method when it calls it.
Parameters
• output (A file-like IO object, or None) – The file-like IO object in which
output should be placed. If None, the method will return the XML output as a string.
• encoding (string) – The encoding that should be used for the output.
• handler (function) – A method that will return a ContentHandler object. This
method will be called with two positional parameters: the output parameter (or, if None, a
file-like IO object) and the encoding parameter.
Returns If output was None, the method will return the XML output as a string. Otherwise, None.
XMLNodeBase.emit_handler(content_handler,
pretty=True,
full_document=None)
Pass the contents of the XML tree to a ContentHandler object.
newl=’\n’,
indent=’
‘,
This method will pass the contents of the XML tree to a ContentHandler object.
Parameters
• content_handler (ContentHandler) – The ContentHandler object to which
the XML tree wll be passed.
• pretty
(bool)
–
If
True,
this
method
will
content_handler.ignorableWhitespace() method to add
48
call
the
Chapter 1. Welcome
jxmlease Documentation, Release 1.0.2dev1
• to the output document. (whitespace) –
• newl (string) – The string which the method should use for new lines when adding
white space (see the pretty parameter).
• indent (text) – The string which the method should use for each level of indentation
when adding white space (see the pretty parameter).
• full_document
(bool)
–
If
True,
the
method
will
call
the
content_handler.startDocument()
and
content_handler.endDocument() methods at the start and end of the document, respectively. If False, it will not call these methods. If the parameter is not set, the
method will attempt to determine whether the current node is the root of an XML tree with
a single root tag. If so, it will set the full_document parameter to True; otherwise, it will set
it to False.
Returns None
1.6.2 Producing XML Output from a Python Object
You can produce XML output from a normal Python dictionary or list using the emit_xml() function.
jxmlease.emit_xml(obj, *args, **kwargs)
Translate a Python dictionary or list to XML output.
This method internally creates an XMLDictNode or XMLListNode object, as appropriate, and then calls the
emit_xml method of that class.
Any arguments you supply are passed on to the emit_xml method of that class. Please see the documentation
for the class’ emit_xml method for information on arguments and return values.
Raises TypeError – If the object is not an appropriate type to convert to an XML tree.
1.7 Module Index
genindex
1.7. Module Index
49
jxmlease Documentation, Release 1.0.2dev1
50
Chapter 1. Welcome
Python Module Index
j
jxmlease, 1
51
jxmlease Documentation, Release 1.0.2dev1
52
Python Module Index
Index
Symbols
__hash__ (jxmlease.EtreeParser attribute), 6
__hash__ (jxmlease.Parser attribute), 4
__add__ (jxmlease.XMLCDATANode attribute), 34
__hash__ (jxmlease.XMLCDATANode attribute), 34
__add__ (jxmlease.XMLListNode attribute), 20
__iadd__ (jxmlease.XMLListNode attribute), 21
__call__() (jxmlease.EtreeParser method), 5
__imul__ (jxmlease.XMLListNode attribute), 21
__call__() (jxmlease.Parser method), 4
__iter__ (jxmlease.XMLListNode attribute), 21
__cmp__ (jxmlease.XMLDictNode attribute), 7
__contains__ (jxmlease.XMLCDATANode attribute), 34 __le__ (jxmlease.XMLCDATANode attribute), 34
__le__ (jxmlease.XMLDictNode attribute), 8
__contains__ (jxmlease.XMLListNode attribute), 20
__le__ (jxmlease.XMLListNode attribute), 21
__contains__() (jxmlease.XMLDictNode method), 7
__len__ (jxmlease.XMLCDATANode attribute), 34
__delattr__ (jxmlease.EtreeParser attribute), 5
__len__ (jxmlease.XMLDictNode attribute), 8
__delattr__ (jxmlease.Parser attribute), 4
__len__ (jxmlease.XMLListNode attribute), 21
__delattr__ (jxmlease.XMLCDATANode attribute), 34
__lt__ (jxmlease.XMLCDATANode attribute), 34
__delattr__ (jxmlease.XMLDictNode attribute), 7
__lt__ (jxmlease.XMLDictNode attribute), 8
__delattr__ (jxmlease.XMLListNode attribute), 20
__lt__ (jxmlease.XMLListNode attribute), 21
__delitem__ (jxmlease.XMLListNode attribute), 21
__mod__ (jxmlease.XMLCDATANode attribute), 34
__delslice__ (jxmlease.XMLListNode attribute), 21
__mul__ (jxmlease.XMLCDATANode attribute), 34
__eq__ (jxmlease.XMLCDATANode attribute), 34
__mul__ (jxmlease.XMLListNode attribute), 21
__eq__ (jxmlease.XMLListNode attribute), 21
__ne__ (jxmlease.XMLCDATANode attribute), 34
__format__() (jxmlease.EtreeParser method), 5
__ne__ (jxmlease.XMLListNode attribute), 21
__format__() (jxmlease.Parser method), 4
__reduce__() (jxmlease.EtreeParser method), 6
__format__() (jxmlease.XMLCDATANode method), 34
__reduce__() (jxmlease.Parser method), 5
__format__() (jxmlease.XMLDictNode method), 7
__reduce__() (jxmlease.XMLCDATANode method), 34
__format__() (jxmlease.XMLListNode method), 21
__reduce__() (jxmlease.XMLListNode method), 21
__ge__ (jxmlease.XMLCDATANode attribute), 34
__reduce_ex__() (jxmlease.EtreeParser method), 6
__ge__ (jxmlease.XMLDictNode attribute), 7
__reduce_ex__() (jxmlease.Parser method), 5
__ge__ (jxmlease.XMLListNode attribute), 21
__reduce_ex__() (jxmlease.XMLCDATANode method),
__getattribute__ (jxmlease.EtreeParser attribute), 5
34
__getattribute__ (jxmlease.Parser attribute), 4
__reduce_ex__()
(jxmlease.XMLDictNode method), 8
__getattribute__ (jxmlease.XMLCDATANode attribute),
__reduce_ex__()
(jxmlease.XMLListNode method), 21
34
__repr__
(jxmlease.EtreeParser
attribute), 6
__getattribute__ (jxmlease.XMLDictNode attribute), 8
__repr__
(jxmlease.Parser
attribute),
5
__getattribute__ (jxmlease.XMLListNode attribute), 21
__reversed__()
(jxmlease.XMLListNode
method), 21
__getitem__ (jxmlease.XMLCDATANode attribute), 34
__rmod__
(jxmlease.XMLCDATANode
attribute),
34
__getitem__() (jxmlease.XMLDictNode method), 8
__rmul__
(jxmlease.XMLCDATANode
attribute),
34
__getitem__() (jxmlease.XMLListNode method), 21
__rmul__ (jxmlease.XMLListNode attribute), 21
__getslice__ (jxmlease.XMLCDATANode attribute), 34
__setattr__ (jxmlease.EtreeParser attribute), 6
__getslice__ (jxmlease.XMLListNode attribute), 21
__setattr__ (jxmlease.Parser attribute), 5
__gt__ (jxmlease.XMLCDATANode attribute), 34
__setattr__ (jxmlease.XMLCDATANode attribute), 35
__gt__ (jxmlease.XMLDictNode attribute), 8
__setattr__ (jxmlease.XMLDictNode attribute), 8
__gt__ (jxmlease.XMLListNode attribute), 21
__setattr__ (jxmlease.XMLListNode attribute), 21
53
jxmlease Documentation, Release 1.0.2dev1
__setitem__ (jxmlease.XMLListNode attribute), 22
__setslice__ (jxmlease.XMLListNode attribute), 22
__sizeof__() (jxmlease.EtreeParser method), 6
__sizeof__() (jxmlease.Parser method), 5
__sizeof__() (jxmlease.XMLCDATANode method), 35
__sizeof__() (jxmlease.XMLDictNode method), 8
__sizeof__() (jxmlease.XMLListNode method), 22
__str__ (jxmlease.EtreeParser attribute), 6
__str__ (jxmlease.Parser attribute), 5
A
add_node() (jxmlease.XMLCDATANode method), 35
add_node() (jxmlease.XMLDictNode method), 8
add_node() (jxmlease.XMLListNode method), 22
append() (jxmlease.XMLListNode method), 22
append_cdata() (jxmlease.XMLCDATANode method),
35
append_cdata() (jxmlease.XMLDictNode method), 9
append_cdata() (jxmlease.XMLListNode method), 22
C
capitalize() (jxmlease.XMLCDATANode method), 36
center() (jxmlease.XMLCDATANode method), 36
clear() (jxmlease.XMLDictNode method), 9
copy() (jxmlease.XMLDictNode method), 9
count() (jxmlease.XMLCDATANode method), 36
count() (jxmlease.XMLListNode method), 22
D
decode() (jxmlease.XMLCDATANode method), 36
delete_xml_attr() (jxmlease.XMLCDATANode method),
36
delete_xml_attr() (jxmlease.XMLDictNode method), 9
delete_xml_attr() (jxmlease.XMLListNode method), 22
dict() (jxmlease.XMLCDATANode method), 36
dict() (jxmlease.XMLDictNode method), 9
dict() (jxmlease.XMLListNode method), 23
F
find() (jxmlease.XMLCDATANode method), 39
find_nodes_with_tag()
(jxmlease.XMLCDATANode
method), 39
find_nodes_with_tag()
(jxmlease.XMLDictNode
method), 12
find_nodes_with_tag()
(jxmlease.XMLListNode
method), 25
format() (jxmlease.XMLCDATANode method), 42
fromkeys() (jxmlease.XMLDictNode method), 15
G
get() (jxmlease.XMLDictNode method), 15
get_cdata() (jxmlease.XMLCDATANode method), 42
get_cdata() (jxmlease.XMLDictNode method), 15
get_cdata() (jxmlease.XMLListNode method), 28
get_current_node()
(jxmlease.XMLCDATANode
method), 42
get_current_node() (jxmlease.XMLDictNode method),
15
get_current_node() (jxmlease.XMLListNode method), 28
get_xml_attr() (jxmlease.XMLCDATANode method), 43
get_xml_attr() (jxmlease.XMLDictNode method), 15
get_xml_attr() (jxmlease.XMLListNode method), 29
get_xml_attrs() (jxmlease.XMLCDATANode method),
43
get_xml_attrs() (jxmlease.XMLDictNode method), 15
get_xml_attrs() (jxmlease.XMLListNode method), 29
H
has_key() (jxmlease.XMLDictNode method), 16
has_node_with_tag()
(jxmlease.XMLCDATANode
method), 43
has_node_with_tag() (jxmlease.XMLDictNode method),
16
has_node_with_tag() (jxmlease.XMLListNode method),
29
has_xml_attrs() (jxmlease.XMLCDATANode method),
E
43
emit_handler() (jxmlease.XMLCDATANode method), 38 has_xml_attrs() (jxmlease.XMLDictNode method), 16
has_xml_attrs() (jxmlease.XMLListNode method), 29
emit_handler() (jxmlease.XMLDictNode method), 11
emit_handler() (jxmlease.XMLListNode method), 24
I
emit_handler() (jxmlease.XMLNodeBase method), 48
emit_xml() (in module jxmlease), 49
index() (jxmlease.XMLCDATANode method), 43
emit_xml() (jxmlease.XMLCDATANode method), 38
index() (jxmlease.XMLListNode method), 29
emit_xml() (jxmlease.XMLDictNode method), 11
insert() (jxmlease.XMLListNode method), 29
emit_xml() (jxmlease.XMLListNode method), 25
isalnum() (jxmlease.XMLCDATANode method), 43
emit_xml() (jxmlease.XMLNodeBase method), 48
isalpha() (jxmlease.XMLCDATANode method), 43
encode() (jxmlease.XMLCDATANode method), 39
isdecimal() (jxmlease.XMLCDATANode method), 43
endswith() (jxmlease.XMLCDATANode method), 39
isdigit() (jxmlease.XMLCDATANode method), 43
EtreeParser (class in jxmlease), 5
islower() (jxmlease.XMLCDATANode method), 43
expandtabs() (jxmlease.XMLCDATANode method), 39
isnumeric() (jxmlease.XMLCDATANode method), 44
extend() (jxmlease.XMLListNode method), 25
isspace() (jxmlease.XMLCDATANode method), 44
54
Index
jxmlease Documentation, Release 1.0.2dev1
istitle() (jxmlease.XMLCDATANode method), 44
isupper() (jxmlease.XMLCDATANode method), 44
items() (jxmlease.XMLDictNode method), 16
iteritems() (jxmlease.XMLDictNode method), 16
iterkeys() (jxmlease.XMLDictNode method), 16
itervalues() (jxmlease.XMLDictNode method), 16
J
jdict() (jxmlease.XMLCDATANode method), 44
jdict() (jxmlease.XMLDictNode method), 16
jdict() (jxmlease.XMLListNode method), 29
join() (jxmlease.XMLCDATANode method), 44
jxmlease (module), 1
K
set_xml_attr() (jxmlease.XMLDictNode method), 18
set_xml_attr() (jxmlease.XMLListNode method), 31
setdefault() (jxmlease.XMLDictNode method), 18
sort() (jxmlease.XMLListNode method), 31
split() (jxmlease.XMLCDATANode method), 46
splitlines() (jxmlease.XMLCDATANode method), 46
standardize() (jxmlease.XMLCDATANode method), 47
standardize() (jxmlease.XMLDictNode method), 18
standardize() (jxmlease.XMLListNode method), 31
startswith() (jxmlease.XMLCDATANode method), 47
strip() (jxmlease.XMLCDATANode method), 47
strip_cdata() (jxmlease.XMLCDATANode method), 47
strip_cdata() (jxmlease.XMLDictNode method), 18
strip_cdata() (jxmlease.XMLListNode method), 32
swapcase() (jxmlease.XMLCDATANode method), 47
keys() (jxmlease.XMLDictNode method), 17
T
L
title() (jxmlease.XMLCDATANode method), 47
translate() (jxmlease.XMLCDATANode method), 47
list() (jxmlease.XMLCDATANode method), 44
list() (jxmlease.XMLDictNode method), 17
list() (jxmlease.XMLListNode method), 30
ljust() (jxmlease.XMLCDATANode method), 45
lower() (jxmlease.XMLCDATANode method), 45
lstrip() (jxmlease.XMLCDATANode method), 45
P
parse() (in module jxmlease), 5
parse_etree() (in module jxmlease), 6
Parser (class in jxmlease), 2
partition() (jxmlease.XMLCDATANode method), 45
pop() (jxmlease.XMLDictNode method), 17
pop() (jxmlease.XMLListNode method), 30
popitem() (jxmlease.XMLDictNode method), 17
prettyprint() (jxmlease.XMLCDATANode method), 45
prettyprint() (jxmlease.XMLDictNode method), 17
prettyprint() (jxmlease.XMLListNode method), 30
R
U
update() (jxmlease.XMLDictNode method), 19
upper() (jxmlease.XMLCDATANode method), 48
V
values() (jxmlease.XMLDictNode method), 19
viewitems() (jxmlease.XMLDictNode method), 19
viewkeys() (jxmlease.XMLDictNode method), 19
viewvalues() (jxmlease.XMLDictNode method), 19
X
XMLCDATANode (class in jxmlease), 32
XMLDictNode (class in jxmlease), 6
XMLListNode (class in jxmlease), 19
Z
zfill() (jxmlease.XMLCDATANode method), 48
remove() (jxmlease.XMLListNode method), 31
replace() (jxmlease.XMLCDATANode method), 45
reverse() (jxmlease.XMLListNode method), 31
rfind() (jxmlease.XMLCDATANode method), 45
rindex() (jxmlease.XMLCDATANode method), 45
rjust() (jxmlease.XMLCDATANode method), 45
rpartition() (jxmlease.XMLCDATANode method), 45
rsplit() (jxmlease.XMLCDATANode method), 46
rstrip() (jxmlease.XMLCDATANode method), 46
S
set_cdata() (jxmlease.XMLCDATANode method), 46
set_cdata() (jxmlease.XMLDictNode method), 17
set_cdata() (jxmlease.XMLListNode method), 31
set_xml_attr() (jxmlease.XMLCDATANode method), 46
Index
55