gpt4 book ai didi

python - 用 python 解析 lxml : how to with objectify

转载 作者:行者123 更新时间:2023-11-28 20:21:42 26 4
gpt4 key购买 nike

我正在尝试读取 spss 文件后面的 xml,我想从 etree 转移到 objectify。

如何将下面的函数转换为返回一个对象化对象?我想这样做是因为 objectify xml 对象对我(作为新手)来说更容易使用,因为它更像 pythonic。

def get_etree(path_file):

from lxml import etree

with open(path_file, 'r+') as f:
xml_text = f.read()
recovering_parser = etree.XMLParser(recover=True)
xml = etree.parse(StringIO(xml_text), parser=recovering_parser)

return xml

我失败的尝试:

def get_etree(path_file):

from lxml import etree, objectify

with open(path_file, 'r+') as f:
xml_text = objectify.fromstring(xml)

return xml

但是我得到这个错误:

lxml.etree.XMLSyntaxError: xmlns:mdm: 'http://www.spss.com/mr/dm/metadatamodel/Arc 3/2000-02-04' is not a valid URI

最佳答案

第一个也是最大的错误是将文件读入字符串并将该字符串提供给 XML 解析器。

Python 将按照您的默认文件编码读取文件(除非您在调用 read() 时指定编码),并且该步骤很可能会破坏除纯 ASCII 文件以外的任何内容。

XML 文件有多种编码方式,您无法预测它们,您真的不应该对它们做出假设。 XML 文件通过 XML 声明解决了这个问题。

<?xml version="1.0" encoding="Windows-1252"?>

XML 解析器将读取该位信息并正确配置自身,然后再读取文件的其余部分。利用那个设施。 切勿对 XML 文件使用 open()read()

幸运的是 lxml 使它变得非常简单:

from lxml import etree, objectify

def get_etree(path_file):
return etree.parse(path_file, parser=etree.XMLParser(recover=True))

def get_objectify(path_file):
return objectify.parse(path_file)

path = r"/path/to/your.xml"
xml1 = get_etree(path)
xml2 = get_objectify(path)

print xml1 # -> <lxml.etree._ElementTree object at 0x02A7B918>
print xml2 # -> <lxml.etree._ElementTree object at 0x02A7B878>

P.S.:如果您确实肯定地必须使用恢复解析器,请认真考虑。 XML 文件是一种数据结构。如果它损坏了(语法无效、不完整、解码错误,随便你怎么说),你真的愿意相信(根据定义未定义)尝试读取它的结果,还是宁愿拒绝它并显示一条错误消息?

我会选择后者。使用恢复解析器可能会在以后导致严重的运行时错误。

关于python - 用 python 解析 lxml : how to with objectify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27276158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com