gpt4 book ai didi

python - 使用 namespace 解析 XML 时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:23 25 4
gpt4 key购买 nike

嗨,我有一个 xml 文件,我想解析它,它看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<SHOP xmlns="http://www.w3.org/1999/xhtml" xmlns:php="http://php.net/xsl">
<SHOPITEM>
<ID>2332</ID>
...
</SHOPITEM>
<SHOPITEM>
<ID>4433</ID>
...
</SHOPITEM>
</SHOP>

我的解析代码是

from lxml import etree

ifile = open('sample-file.xml', 'r')
file_data = etree.parse(ifile)

for item in file_data.iter('SHOPITEM'):
print item

但项目只有在xml容器时才会打印

<SHOP xmlns="http://www.w3.org/1999/xhtml" xmlns:php="http://php.net/xsl">

看起来像

<SHOP>

我如何解析 xml 文档而不用担心这个容器定义?

最佳答案

参见 here有关 lxml.etree 如何处理命名空间的解释。通常,您应该与它们一起工作而不是试图避开它们。在这种情况下,写:

for item in file_data.iter('{http://www.w3.org/1999/xhtml}SHOPITEM'):

如果需要经常引用命名空间,设置一个局部变量:

xhtml_ns = '{http://www.w3.org/1999/xhtml}'
...
for item in file_data.iter(xhtml_ns + 'SHOPITEM'):

关于python - 使用 namespace 解析 XML 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3634420/

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