Fixed ElementBase._fix_ns and related methods to respect namespaces which contain forward slashes.

This commit is contained in:
Lance Stout 2010-08-26 18:18:00 -04:00
parent 56766508b3
commit 00d7952001

View file

@ -507,7 +507,7 @@ class ElementBase(object):
keep -- Indicates if the element should be kept if its text is keep -- Indicates if the element should be kept if its text is
removed. Defaults to False. removed. Defaults to False.
""" """
name = self._fix_ns(name) path = self._fix_ns(name, split=True)
element = self.xml.find(name) element = self.xml.find(name)
if not text and not keep: if not text and not keep:
@ -520,7 +520,7 @@ class ElementBase(object):
# of generating new elements. # of generating new elements.
last_xml = self.xml last_xml = self.xml
walked = [] walked = []
for ename in name.split('/'): for ename in path:
walked.append(ename) walked.append(ename)
element = self.xml.find("/".join(walked)) element = self.xml.find("/".join(walked))
if element is None: if element is None:
@ -545,8 +545,7 @@ class ElementBase(object):
all -- If True, remove all empty elements in the path to the all -- If True, remove all empty elements in the path to the
deleted element. Defaults to False. deleted element. Defaults to False.
""" """
name = self._fix_ns(name) path = self._fix_ns(name, split=True)
path = name.split("/")
original_target = path[-1] original_target = path[-1]
for level, _ in enumerate(path): for level, _ in enumerate(path):
@ -755,21 +754,33 @@ class ElementBase(object):
""" """
return self return self
def _fix_ns(self, xpath): def _fix_ns(self, xpath, split=False):
""" """
Apply the stanza's namespace to elements in an XPath expression. Apply the stanza's namespace to elements in an XPath expression.
Arguments: Arguments:
xpath -- The XPath expression to fix with namespaces. xpath -- The XPath expression to fix with namespaces.
split -- Indicates if the fixed XPath should be left as a
list of element names with namespaces. Defaults to
False, which returns a flat string path.
""" """
fixed = []
ns_blocks = xpath.split('{')
for ns_block in ns_blocks:
if '}' in ns_block:
namespace = ns_block.split('}')[0]
elements = ns_block.split('}')[1].split('/')
else:
namespace = self.namespace
elements = ns_block.split('/')
def fix_ns(name): for element in elements:
"""Apply namespace to an element if needed.""" if element:
if "}" in name: fixed.append('{%s}%s' % (namespace,
return name element))
return "{%s}%s" % (self.namespace, name) if split:
return fixed
return "/".join(map(fix_ns, xpath.split("/"))) return '/'.join(fixed)
def __eq__(self, other): def __eq__(self, other):
""" """