【问题标题】:Problem parsing XML with namespaces使用命名空间解析 XML 时出现问题
【发布时间】:2011-04-07 18:12:30
【问题描述】:

嗨,我有想要解析的 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 文档而不用担心这个容器定义?

【问题讨论】:

    标签: python xml parsing lxml xml-parsing


    【解决方案1】:

    有关 lxml.etree 如何处理命名空间的说明,请参阅 here。一般来说,您应该与他们合作而不是试图避免他们。在这种情况下,写:

    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'):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-16
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 2021-05-03
      • 2014-01-10
      相关资源
      最近更新 更多