有人对如何使用lxml.objectify和recover=True有什么建议吗?
我的xml属性没有引用--> name=value,而不是name='value‘。
下面是一些示例代码..。我没有对XML格式的控制,所以我不能回去修改它。etree解析确实有效。
错误是
File "<string>", line unknown
XMLSyntaxError: AttValue: " or ' expected, line 4, column 21lxml.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发布于 2016-03-23 05:04:16
更新:
结果,您可以将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=True组合起来,以修复破损的XML输入,然后将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))https://stackoverflow.com/questions/36169791
复制相似问题