Python Elementtree问题写入文件

时间:2019-05-22 07:59:20

标签: python-2.7 elementtree

嗨,我是python的新手,在这里,我有很长时间一直在努力的代码:

#listing all objects
if object_type != 'virtual':
    object_rt_lst = req_lib.list_objects(object_type).getroot()
else:
    object_rt_lst = req_lib.list_virtuals().getroot()

#name of generated file
xmlNm = syscode+'-'+object_type+'.xml'

#composing path
finalpath = os.path.join(output_path, xmlNm)

if object_type == 'virtual':
    object_type = 'virtualResource'

#base structure of xml tree for all objects
base_tree = '''
<UACSystem name="">
<UAC{}s>
</UAC{}s>
</UACSystem>
'''.format(object_type, object_type)

search_elm = 'UAC{}s'.format(object_type)             

#parsing  xml
object_root = ET.ElementTree().getroot()
tgt_xml = ET.fromstring(base_tree)

#for every name of listed objects request their definition
for obj_nm in object_rt_lst.iter('name'):
    #if tenant code in obj_nm.text
    object = obj_nm.text
    if object.startswith(syscode):
         try:
            object_root = req_lib.get_object(object).getroot()
        except:
           #temporary pass objects with invalid names
            pass
    tgt_xml.find(search_elm).append(object_root)
    print type(tgt_xml)

#delete sysIds, retainSysIds to false
for elmt in tgt_xml.findall('sysId'):
    elmt.text=''
#changing attributes: retainSysId to False 
for elmt in tgt_xml.findall("[@retainSysIds]"):
    elmt.attrib['retainSysIds']='false'
#removing version attribute
for elmt in tgt_xml.findall("[@version]"):
   elmt.attrib.pop('version', None)

#saving final workflow
tree = ET.ElementTree(tgt_xml)
tree_str = ET.tostring(finalpath)

#saving file
with open(finalpath, "wb") as tgt_f:
   tgt_f.write(tree)

我创建了一些基础xml,应根据对象类型进行更新。然后,我得到给定对象的列表,从中解析它们的名称,获取它们的xml定义并附加基本xml。然后进行一些“清洗”。最后,我想将创建的xml保存到文件中。但是清洗和保存不起作用。我认为 tgt_xml 一直在造成问题,但是我找不到位置。

实际代码给我错误:

Traceback (most recent call last):
  File "system_uac_export.py", line 101, in <module>
    tree_str = ET.tostring(finalpath)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1126, in 
tostring
    ElementTree(element).write(file, encoding, method=method)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 817, in write
    self._root, encoding, default_namespace
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 876, in 
_namespaces
   iterate = elem.getiterator # cET compatibility
AttributeError: 'str' object has no attribute 'getiterator'

进行其他更改后,会引发我和“ NonType”错误。

有人可以帮助我吗?

0 个答案:

没有答案