def _parse_annotation_xml(filepath):
tree = et.parse(filepath)
data = tree.getroot()[1] # <data>
for sf in data: # <sourcefile> ... find first non-empty sourcefile node
if len(list(sf)) != 0:
break
file = sf[0] # <file>
objs = sf[1:] # <object> ...
num_objs = len(objs)
num_frames = int(file.find("./*[@name='NUMFRAMES']/*[@value]").attrib['value'])
parsed_bbx = np.zeros([num_frames, num_objs, 4])
for i, obj in enumerate(objs): # iterate <object> nodes
loc = obj.find("./*[@name='Location']")
for bbx in loc:
span = re.findall(r'\d+', bbx.attrib['framespan'])
beg, end = int(span[0]), int(span[1])
h = int(bbx.attrib['height'])
w = int(bbx.attrib['width'])
x = int(bbx.attrib['x'])
y = int(bbx.attrib['y'])
parsed_bbx[beg-1:end, i] = [h, w, x, y]
return parsed_bbx
python类parse()的实例源码
def translate_to_text(results_file, text_file):
f = open(text_file, 'w')
import xml.etree.ElementTree as ET
et = ET.parse (results_file)
for test in et.findall('Test'):
node_to_text (test, f)
for example in et.findall('Example'):
result = example.find('Result').text
name = example.find('Name').text
if not example.find('Time') is None:
time_real = example.find('Time').get('real')
else:
time_real = ''
output = "%s: Example \"%s\" (%s)\n" % (result, name, time_real)
f.write(output)
f.close()
#
# A simple example of writing an HTML file with a test result summary. It is
# expected that this will eventually be made prettier as time progresses and
# we have time to tweak it. This may end up being moved to a separate module
# since it will probably grow over time.
#
def _le_xml(self, arquivo):
if arquivo is None:
return False
if not isinstance(arquivo, basestring):
arquivo = etree.tounicode(arquivo)
if arquivo is not None:
if isinstance(arquivo, basestring):
if NAMESPACE_NFSE in arquivo:
arquivo = por_acentos(arquivo)
if u'<' in arquivo:
self._xml = etree.fromstring(tira_abertura(arquivo))
else:
arq = open(arquivo)
txt = ''.join(arq.readlines())
txt = tira_abertura(txt)
arq.close()
self._xml = etree.fromstring(txt)
else:
self._xml = etree.parse(arquivo)
return True
return False
def validar(self):
arquivo_esquema = self.caminho_esquema + self.arquivo_esquema
# Aqui é importante remover a declaração do encoding
# para evitar erros de conversão unicode para ascii
xml = tira_abertura(self.xml).encode(u'utf-8')
esquema = etree.XMLSchema(etree.parse(arquivo_esquema))
if not esquema.validate(etree.fromstring(xml)):
for e in esquema.error_log:
if e.level == 1:
self.alertas.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))
elif e.level == 2:
self.erros.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))
return esquema.error_log
def xml_start(xml):
'Stores $xml file in $dicc dictionary'
def xml_parse(root, dicc, way=""):
new_way = way + "/" + root.tag
value = []
try:
value = dicc[new_way]
except:
value = []
value.append(root.text)
dicc.__setitem__(new_way, value)
for new_root in root._children:
xml_parse(new_root, dicc, new_way)
tree = ET.parse(xml, parser=None)
root = tree.getroot()
dicc = {}
xml_parse(root, dicc, way="")
return dicc
def getByID(id):
try:
en_tree = ET.parse('lib/lang/en.xml')
de_tree = ET.parse('lib/lang/de.xml')
except FileNotFoundError:
print(BOLD + RED + "ERROR: Didn't find en.xml or de.xml in lib/lang/\n" +
" Please clone this project again from GitHub!" + ENDC)
sys.exit(0)
string = '''.//*[@id='%ID%']'''
string = str(string).replace("%ID%", id)
if language.__contains__("de"):
return de_tree.findall(string)[0].text
else:
return en_tree.findall(string)[0].text
testcase_utils_class.py 文件源码
项目:warriorframework
作者: warriorframework
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def append_result_files(self, dst_resultfile, kw_resultfile_list, dst_root='Testcase', childtag='Keyword'):
"""Append kw/system result files into a testcase result file"""
try:
finstring = ''
for kw_file in kw_resultfile_list:
if kw_file is not None and kw_file is not False:
tree = self.xml_utils().get_tree_from_file(kw_file)
self.root = tree.getroot()
for child in self.root:
if child.tag == childtag:
finstring = finstring+self.xml_utils().convert_element_to_string(child)
tc_string = ' '
if self.file_utils().fileExists(dst_resultfile):
tc_tree = ET.parse(dst_resultfile)
tc_root = tc_tree.getroot()
for tc_child in tc_root:
tc_string = tc_string+self.xml_utils().convert_element_to_string(tc_child)
finalresult = '\n'.join(['<{0}>'.format(dst_root), tc_string + finstring,
'</{0}>'.format(dst_root)])
with open(dst_resultfile, 'w') as resultfile:
resultfile.write(finalresult)
resultfile.flush()
resultfile.close()
except Exception, err:
print_info('unexpected error: {0}'.format(str(err)))
configuration_element_class.py 文件源码
项目:warriorframework
作者: warriorframework
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def parse_tree(self, node):
"""
Method to parse ElementTree to ConfigurationElement Tree
:param node:
:return:
"""
for key in node.attrib:
self.attributes[key] = node.attrib[key]
self.attributes['xml_tag'] = node.tag
# self.attributes['xml_element'] = node
for child in node:
try:
if not child.attrib['name'] in self.children:
child_config = ConfigurationElement(child.attrib['name'])
child_config.parse_data(child, root=False)
self.children[child.attrib['name']] = child_config
else:
self.children[child.attrib['name']].parse_tree(child)
except KeyError:
print_error("No name attribute for node " + child.tag + ". Tree with root "
"at node " + child.tag + " not parsed.")
def evaluate_argument_value(xpath_or_tagname, datafile):
"""This function takes checks if the given xpath_or_tagname exists in the
datafile and returns its value. Else returns None."""
tree = ET.parse(datafile)
root = tree.getroot()
if xpath_or_tagname.startswith(root.tag + "/"):
xpath_or_tagname = xpath_or_tagname[len(root.tag + "/"):]
try:
xpath_or_tagname = root.find(xpath_or_tagname).text
except Exception:
print_error("Invalid xpath: {0}".format(root.tag + "/" + xpath_or_tagname))
xpath_or_tagname = None
else:
print_error("Invalid xpath: {0}".format(xpath_or_tagname))
xpath_or_tagname = None
return xpath_or_tagname
def getChildTextbyParentAttribute (datafile, pnode, patt, pattval, cnode):
"""
Seraches XML file for the parent node with a specific value. Finds the child node and returns
its text
datafile = xml file searched
pnode = parent node
patt = parent node attribute
patval = parent node attribute value
cnode = child node
"""
tree = ElementTree.parse(datafile)
root = tree.getroot()
value = False
for node in root.findall(pnode):
attribute = node.get(patt)
if attribute == pattval:
cnode = node.find(cnode)
if cnode is not None:
value = cnode.text
else:
return None
break
return value
def getChildTextbyParentTag (datafile, pnode, cnode):
"""
Seraches XML file for the first parent. Finds the child node and returns its text
datafile = xml file searched
pnode = parent node
cnode = child node
"""
value = False
tree = ElementTree.parse(datafile)
root = tree.getroot()
node = root.find(pnode)
if node is not None:
child = node.find(cnode)
if child is not None:
value = child.text
return value
else:
# print_info("could not find cnode under the given pnode")
return value
else:
# print_info("could not find pnode in the provided file")
return value
def getChildAttributebyParentTag (datafile, pnode, cnode, cattrib):
"""Find the attribute in child node by traversing through the parent node
in the given file
datafile = xml file searched
pnode = parent node
cnode = child node
cattrob = child node attrib
"""
tree = ElementTree.parse(datafile)
root = tree.getroot()
node = root.find(pnode)
if node is not None:
child = node.find(cnode)
if child is not None:
value = child.get(cattrib)
return value
else:
# print_info("could not find cnode under the given pnode")
return False
else:
# print_info("could not find pnode in the provided file")
return False
def verifyParentandChildrenMatch (datafile, pnode, cnode, cvalue, rnode, rvalue):
"""
Searches XML file for the parent node. Finds the 1st child node and checks its value
if value is a match, then search for second child and check if its value matches
datafile = xml file searched
pnode = parent node
cnode = child node
cvalue = child node value
rnode = reference node
rvalue = refernce node value
"""
tree = ElementTree.parse(datafile)
root = tree.getroot()
status = False
for node in root.findall(pnode):
value = node.find(cnode).text
if value == cvalue:
if node.find(rnode) is not None:
cnodev = node.find(rnode).text
# print_debug("-D- cnodev: '%s', rvalue : '%s'" % (cnodev, rvalue))
if cnodev == rvalue:
# print_debug("-D- BREAK END METHOD verifyParentandChildrenMatch_Status '%s'" % status)
return True
return status
def getElementsListWithTagAttribValueMatch(datafile, tag, attrib, value):
"""
This method takes an xml document as input and finds all the sub elements (parent/children)
containing specified tag and an attribute with the specified value.
Returns a list of matching elements.
Arguments:
datafile = input xml file to be parsed.
tag = tag value of the sub-element(parent/child) to be searched for.
attrib = attribute name for the sub-element with above given tag should have.
value = attribute value that the sub-element with above given tag, attribute should have.
"""
element_list = []
root = ElementTree.parse(datafile).getroot()
for element in root.iterfind(".//%s[@%s='%s']" % (tag, attrib, value)):
element_list.append(element)
return element_list
def getElementWithTagAttribValueMatch(start, tag, attrib, value):
"""
When start is an xml datafile, it finds the root and first element with:
tag, attrib, value.
Or when it's an xml element, it finds the first child element with:
tag, attrib, value.
If there is not a match, it returns False.
"""
node = False
if isinstance(start, (file, str)):
# check if file exist here
if file_Utils.fileExists(start):
node = ElementTree.parse(start).getroot()
else:
print_warning('The file={0} is not found.'.format(start))
elif isinstance(start, ElementTree.Element):
node = start
if node is not False and node is not None:
elementName = ".//%s[@%s='%s']" % (tag, attrib, value)
element = node.find(elementName)
else:
element = node
return element
def getConfigElementTextWithSpecificXpath(datafile, xpath):
"""
This method takes an xml document as input and finds the first sub element (parent/children)
containing specified xpath which should be a filepath to a netconf config file
Returns the element text attribute
Arguments:
parent = parent element
xpath = a valid xml path value as supported by python, refer https://docs.python.org/2/library/xml.etree.elementtree.html
"""
root = ElementTree.parse(datafile).getroot()
elem1 = root.find(xpath).text
elem2_root = ElementTree.parse(elem1)
elem2 = elem2_root.find('config')
elem2_string = ElementTree.tostring(elem2)
return elem2_string
def getChildElementWithSpecificXpath(start, xpath):
"""
This method takes a xml file or parent element as input and finds the first child
containing specified xpath
Returns the child element.
Arguments:
start = xml file or parent element
xpath = a valid xml path value as supported by python, refer https://docs.python.org/2/library/xml.etree.elementtree.html
"""
node = False
if isinstance(start, (file, str)):
# check if file exist here
if file_Utils.fileExists(start):
node = ElementTree.parse(start).getroot()
else:
print_warning('The file={0} is not found.'.format(start))
elif isinstance(start, ElementTree.Element):
node = start
if node is not False or node is not None:
element = node.find(xpath)
else:
element = False
return element
def del_tags_from_xml(xml, tag_list=[]):
"""
It deletes the tags either by their names or xpath
Arguments:
1.xml: It takes xml file path or xml string as input
2.tag_list: It contains list of tags which needs to be removed
Returns:
It returns xml string
"""
if os.path.exists(xml):
tree = ElementTree.parse(xml)
root = tree.getroot()
else:
root = ElementTree.fromstring(xml)
for tag in tag_list:
if 'xpath=' in tag:
tag = tag.strip('xpath=')
req_tags = getChildElementsListWithSpecificXpath(root, tag)
else:
req_tags = getChildElementsListWithSpecificXpath(root, ".//{0}".format(tag))
recursive_delete_among_children(root, req_tags)
xml_string = ElementTree.tostring(root, encoding='utf-8', method='xml')
return xml_string
def convert_xml_to_list_of_dict(file_name):
"""
Takes xml file path as input and
converts to list of dictionaries
Arguments:
file_name : It takes xml file path as input
Returns:
list_of_dict: list of dictionaries where keys
are tag names and values are respective text of the tag.
"""
tree = ElementTree.parse(file_name)
root = tree.getroot()
list_of_dict = []
for child in root:
subchild_dict = OrderedDict()
for subchild in child:
subchild_dict[subchild.tag] = subchild.text
list_of_dict.append(subchild_dict)
return list_of_dict
#2016/06/22 ymizugaki add begin
def get_node(filename, node_name):
""" Searches for the specified node in the xml tree.
return type: xml.etree.ElementTree.Element
:Arguments:
1. node_name (str) = Name of the node to be searched
2. filename (str) = path of the .xml that has to be searched.
:Returns:
node = xml.etree.ElementTree.Element/boolean False
"""
root = ElementTree.parse(filename).getroot()
node = root.find(node_name)
if node is not None:
return node
else:
return False