XMLCDATANode Ojbects¶
-
class
jxmlease.
XMLCDATANode
(*args, **kwargs)[source]¶ 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.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. (Note
that this is ignored for
XMLCDATANode
objects.) - 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), theconvert()
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
-
__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)[source]¶ 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 anXMLDictNode
so that it can hold children. If the current node is anXMLDictNode
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 anXMLCDATANode
object. If supplied, these additional keyword parameters are passed to theXMLCDATANode.__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 theXMLCDATANode
. If supplied, thetext
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 (Seeget_current_node()
) or the method encounters irrecoverable data inconsistency while making changes to the XML tree.TypeError
– Ifnew_node
is not None and not an instance ofXMLNodeBase
-
append_cdata
(cdata, return_node=False)[source]¶ 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 thereturn_node
parameter to True or by running theget_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. (Seeget_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 theattr
is not found.AttributeError
– If the node is out of date. (Seeget_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
, andfunc
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 theattrs
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):
- The attributes in the attrs parameter, in the order they appear in the attrs parameter.
- The tags in the tags parameter, in the order they appear in the attrs parameter.
- The return value of the user-supplied function.
- 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
andpromote
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:
- 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.
- 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
. Ifin_place
is False, the dictionary formulated from the current node. Ifin_place
is True, the dictionary to which the nodes were added. (Note: Ifpromote
is True, this dictionary may contain additional entries that already existed in the enclosing dictionary.)Raises: AttributeError
– If the node is out of date andin_place
is True. (Seeget_current_node()
.)AttributeError
– Ifin_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
) – TheContentHandler
object to which the XML tree wll be passed. - pretty (bool) – If True, this method will call the
content_handler.ignorableWhitespace()
method to add - 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()
andcontent_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
- content_handler (
-
emit_xml
(output=None, encoding='utf-8', handler=<class xml.sax.saxutils.XMLGenerator>, **kwargs)¶ Return the contents of the XML tree as an XML document.
This method will create a
ContentHandler
by calling the method provided by the handler parameter. It will callemit_handler()
with thisContentHandler
object. In addition, this method will accept any parameter that theemit_handler()
method accepts (except thecontent_handler
parameter). It will pass them to theemit_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 therecursive
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:
>>> 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 taglessXMLDictNode
, rather than searching the children of the taglessXMLDictNode
:>>> 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 ... {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 therecursive
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 arecursive
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:" ... 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_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 theattr
is not found anddefval
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 thefind_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.
-
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 thedict()
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
. Ifin_place
is False, the dictionary formulated from the current node. Ifin_place
is True, the dictionary to which the nodes were added. (Note: Ifpromote
is True, this dictionary may contain additional entries that already existed in the enclosing dictionary.)Raises: AttributeError
– If the node is out of date andin_place
is True. (Seeget_current_node()
.)AttributeError
– Ifin_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.
-
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 andin_place
is True. (Seeget_current_node()
.)
-
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)[source]¶ Print a “pretty” representation of the data structure.
This uses the
pprint()
method from thepprint
module to print a “pretty” representation of the data structure. The parameters are passed unchanged to thepprint()
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).
-
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)[source]¶ Set a node’s CDATA.
This method sets 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 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. (Seeget_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. (Seeget_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.
-
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)[source]¶ 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 tonode.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 theget_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. (Seeget_current_node()
.)- chars (string) – Contains the characters to strip. This is passed to
the string class’
-
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.
-
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.