我正在尝试在内存中创建一个大型 XML 文件,该文件将插入到 ESRI 要素类的 Blob 字段中。
我尝试使用 elementtree,但 Python 最终会崩溃。我可能没有以最好的方式做到这一点。我的代码示例(不准确):
with update_cursor on feature class:
for row in update_cursor:
root = Element("root")
tree = ElementTree(root)
for id in id_list:
if row[0] in id:
equipment = Element("equipment")
root.append(equipment)
attrib1 = Element("attrib1")
equipment.append(attrib1)
attrib1.text = "myattrib1"
attrib2 = Element("attrib2")
equipment.append(attrib2)
attrib2.text = "myattrib2"
....and about 5 more of these appended to equipment
xml_data = ET.tostring(root)
insert xml_data into blob field
XML 示例:
<root>
<equipment>
<attrib1>One</attrib1>
<attrib2>Two</attrib2>
<attrib3>Three</attrib3>
...
<attrib10>Ten</attrib10>
</equipment>
<equipment>
<attrib1>One</attrib1>
<attrib2>Two</attrib2>
<attrib3>Three</attrib3>
...
<attrib10>Ten</attrib10>
</equipment>
</root>
现在我意识到这可能是一种相当业余的方法,但我不确定在内存中构建此 XML 的最佳方法。
对于 update_cursor 中的每一行,可以将多个“equipment”元素添加到根,并且每个“equipment”元素将具有完全相同的子元素,但具有不同的属性。
我运行了这个,大约有 200 个 id 与单行匹配,因此它必须在内存中创 build 备元素和设备的所有子元素 200 次。
那么使用标准库通过 Python 在内存中创建 XML 的最佳方法是什么?
最佳答案
你的数据结构看起来非常简单。不必费心使用 XML 库。只需将您的行直接写入 cStringIO.StringIO
即可。
with update_cursor on feature class:
for row in update_cursor:
buffer = cStringIO.StringIO()
buffer.write("<root>\n")
for id in id_list:
if row[0] in id:
buffer.write(" <equipment>\n")
buffer.write(" <attrib1>One</attrib1>\n")
buffer.write(" <attrib2>Two</attrib2>\n")
buffer.write(" <attrib3>Three</attrib3>\n")
....and about 5 more of these appended to equipment
buffer.write(" </equipment>\n")
buffer.write("</root>\n")
xml_data = buffer.getvalue()
insert xml_data into blob field
关于python - 如何使用Python标准库在内存中构建大型XML文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260676/