我有一个功能,可以向xml发送get请求并解析响应:
def get_object(object_name):
...
...
#parse xml file
encoded_text = response.text.encode('utf-8', 'replace')
root = ET.fromstring(encoded_text)
tree = ET.ElementTree(root)
return tree
然后,我使用此函数遍历列表中的对象以获取xml并将其存储在变量中:
jx_task_tree = ''
for jx in jx_tasks_lst:
jx_task_tree += str(get_object(jx))
我不确定,该函数是否以正确的格式/格式向我返回数据,以便以后按需要使用它们。
当我想像这样解析变量jx_task_tree时:
parser = ET.XMLParser(encoding="utf-8")
print(type(jx_task_tree))
tree = ET.parse(jx_task_tree, parser=parser)
print(ET.tostring(tree))
它抛出一个错误:
Traceback (most recent call last):
File "import_uac_wf.py", line 59, in <module>
tree = ET.parse(jx_task_tree, parser=parser)
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1182, in
parse
tree.parse(source, parser)
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 647, in parse
source = open(source, "rb")
IOError: [Errno 36] File name too long:
'<xml.etree.ElementTree.ElementTree
object at 0x7ff2607c8910>\n<xml.etree.ElementTree.ElementTree object at
0x7ff2607e23d0>\n<xml.etree.ElementTree.ElementTree object at
0x7ff2607ee4d0>\n<xml.etree.ElementTree.ElementTree object at
0x7ff2607d8e90>\n<xml.etree.ElementTree.ElementTree object at
0x7ff2607e2550>\n<xml.etree.ElementTree.ElementTree object at
0x7ff2607889d0>\n<xml.etree.ElementTree.ElementTree object at
0x7ff26079f3d0>\n'
有人会帮助我吗,函数get_object()应该返回什么以及以后如何使用它,那么返回的内容可以加入一个变量并进行解析?
答案 0 :(得分:1)
关于您当前的例外情况:
根据[Python 3.Docs]: xml.etree.ElementTree.parse(source, parser=None)(强调是我的):
将XML部分解析为元素树。 源是包含XML数据的文件名或文件对象。
如果要从字符串加载 XML ,请改用ET.fromstring
。
那么,正如您所怀疑的那样,第二个 nd 代码段是完全错误的:
get_object(jx)
返回已经解析的 XML ,因此返回 ElementTree 对象您可以执行以下操作:
jx_tasks_string = ""
for jx in jx_tasks_lst:
jx_tasks_string += ET.tostring(get_object(jx).getroot())
由于 jx_tasks_string 是通过解析某些 XML blob获得的某些字符串的串联,因此没有理由再次对其进行解析。