2

有人对如何使用lxml.objectifywith有任何提示recover=True吗?

我有没有引用属性的 xml --> name=value 而不是 name='value'。

下面是一些示例代码...我无法控制 XML 格式,所以我无法返回并更改它。解析etree确实有效

错误是

File "<string>", line unknown
XMLSyntaxError: AttValue: " or ' expected, line 4, column 21

lxml.objectify代码——失败

xmlSample="""<dict>
<maptable>
  <hdterm displevel=1 autlookup entrytype=1>Source term</hdterm>
</maptable>
</dict>"""

如果我没有得到答案,我是否必须重新

import io
#p = objectify.XMLParser(recover=True)

root = objectify.fromstring(xmlSample)

# returns attributes in element node as dict
attrib = root.getattrib()

# how to extract element data
tbl = root.mytable

print("root.mytable type=%s" % type(tbl))

lxml.etree- 工作!

from lxml import etree, objectify

import io
xmlIO = io.StringIO(xmlSample)

p = etree.XMLParser(recover=True)

tree = etree.parse(xmlIO, parser=p)
root = tree.getroot()
print(root.tag)

输出:

myxml
4

1 回答 1

1

更新 :

原来,您可以通过recover=True选项来objectify.makeparser()创建一个解析器,该解析器将尝试恢复格式错误的 XML 文档。然后您可以将创建的解析器传递给objectify.fromstring(),如下所示:

from lxml import etree, objectify

xmlSample="""<dict>
<maptable>
  <hdterm displevel=1 autlookup entrytype=1>Source term</hdterm>
</maptable>
</dict>"""

parser = objectify.makeparser(recover=True)
root = objectify.fromstring(xmlSample, parser)

print(type(root.maptable.hdterm))
# output :
# <type 'lxml.objectify.StringElement'>

初步答案:

您可以将两者结合起来;etree修复损坏的recover=TrueXML 输入,然后objectify解析格式良好的中间 XML:

from lxml import etree, objectify

xmlSample="""your_xml_here"""

p = etree.XMLParser(recover=True)
well_formed_xml = etree.fromstring(xmlSample, p)
root = objectify.fromstring(etree.tostring(well_formed_xml))
于 2016-03-23T05:04:16.620 回答