lxml解析py-postgresql xml输出

时间:2017-10-30 08:50:50

标签: python xml postgresql lxml

我在PostgreSQL中有sql-query返回xml类型的行。我想将这些行附加到python中的lxml元素。

from lxml import etree as ET
#doing db connection here, declare a query text etc.

root = ET.Element('root')
res = db.query(querytext)
for row in res:
  root.append(row[0]) #<- and here i'm getting error

错误是“预期lxml.etree._element得到了xml.etree.ElementTree.element”

那么如何将xml.etree.ElementTree.element转换为lxml.etree._element?或者我需要以其他方式做到这一点?另一个xml lib可能吗?

1 个答案:

答案 0 :(得分:0)

您需要从字符串创建xml:

from lxml import etree as ET
#doing db connection here, declare a query text etc.

root = ET.Element('root')
#res = db.query(querytext)

res = [
    ('<foo>1</foo>', ),
    ('<foo>2</foo>', )
]

for row in res:
  root.append(ET.fromstring(row[0]))

print(ET.tostring(root, pretty_print=True))

返回:

b'<root>\n  <foo>1</foo>\n  <foo>2</foo>\n</root>\n'