gpt4 book ai didi

带有命名空间的 Python xml 解析器

转载 作者:行者123 更新时间:2023-12-04 17:05:22 24 4
gpt4 key购买 nike

亲爱的,
我有一个像下面这样的 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<Data xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/xxxx//bb/v1 /xyz/it/Data/v1/Data-1_2.xsd" version="1.2" xmlns="http://xx/it//Data/v1">
<Header>
<Location>abc</Location>
<Date start="date-time"/>
我正在尝试解析不同的标签和属性。然而,xmln 似乎搞乱了解析。
我正在使用类似的代码
tree = ET.parse(input_filename)
root = tree.getroot()
location = tree.find("./Header/Location").text
time = tree.find("./Header/Date").attrib['start']
当我从输入文件中手动删除 <?xml version="1.0" encoding="utf-8"?>
<Data >
<Header>
<Location>abc</Location>
<Date start="date-time"/>
但保持它会出错
location = tree.find("./Header/Location").text
AttributeError: 'NoneType' object has no attribute 'text'
我尝试了几乎 90% 的先前建议仍然没有好的结果。
高度赞赏。

最佳答案

现代 Python 版本支持命名空间的通配符。考虑一下:-

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="utf-8"?>
<Data xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/xxxx//bb/v1 /xyz/it/Data/v1/Data-1_2.xsd" version="1.2" xmlns="http://xx/it//Data/v1">
<Header>
<Location>abc</Location>
<Date start="date-time"/>
</Header>
</Data>'''

tree = ET.fromstring(xml)

location = tree.find('.//{*}Header/{*}Location').text
_time = tree.find('.//{*}Header/{*}Date').attrib['start']

print(f'Location={location}, time={_time}')

关于带有命名空间的 Python xml 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68905759/

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