python - 如何使用Python标准库在内存中构建大型XML文档?

标签 python xml in-memory

我正在尝试在内存中创建一个大型 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/

相关文章:

python - 从 QLineEdit 中提取文本

javascript - 使用 jQuery 在 TextArea 中显示 xml

database - 将现有的 Sqlite 数据库加载到内存中以进行快速计算

.net 2.0 : What's the best way to deal with in-memory DataTables?

node.js - 在服务器内存中生成 zip 文件并作为下载 Node.JS 发送到客户端

python - python httplib 的各种超时

python - openerp 服务器操作 - python 代码

python - Django ORM 优化 - 按计数以及注释过滤器的最后一个条目进行注释

json - 是否有用于从一张表中读取行的 RESTful Google Sheets API?

java - 如何使用 Java 从 Excel (XLSX) 构建 XML