【问题标题】:Parse xml from file using etree works when reading string, but not a file使用 etree 从文件中解析 xml 在读取字符串时有效,但不是文件
【发布时间】:2013-02-28 04:36:33
【问题描述】:

我是 Python 和 SO 的新手。我有一个需要从中提取信息的 xml 文件。我已经为此苦苦挣扎了好几天,但我想我终于找到了可以正确提取信息的东西。现在我很难获得正确的输出。这是我的代码:

from xml import etree
node = etree.fromstring('<dataObject><identifier>5e1882d882ec530069d6d29e28944396</identifier><description>This is a paragraph about a shark.</description></dataObject>')
identifier = node.findtext('identifier')
description = node.findtext('description')
print identifier, description

我得到的结果是“5e1882d882ec530069d6d29e28944396 这是一个关于鲨鱼的段落。”,这就是我想要的。

但是,我真正需要的是能够从文件而不是字符串中读取。所以我试试这段代码:

from xml import etree
node = etree.parse('test3.xml')
identifier = node.findtext('identifier')
description = node.findtext('description')
print identifier, description

现在我的结果是“无无”。我有一种感觉,我要么没有正确获取文件,要么输出有问题。这是test3.xml的内容

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response xmlns="http://www.eol.org/transfer/content/0.3" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dwc="http://rs.tdwg.org/dwc/dwcore/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:dwct="http://rs.tdwg.org/dwc/terms/" xsi:schemaLocation="http://www.eol.org/transfer/content/0.3 http://services.eol.org/schema/content_0_3.xsd">
  <identifier>5e1882d822ec530069d6d29e28944369</identifier>
  <description>This is a paragraph about a shark.</description>

【问题讨论】:

    标签: python xml xml-parsing xml.etree


    【解决方案1】:

    您的 XML 文件使用默认命名空间。您需要使用正确的命名空间来限定您的搜索:

    identifier = node.findtext('{http://www.eol.org/transfer/content/0.3}identifier')
    

    让 ElementTree 匹配正确的元素。

    您还可以为.find()findall()iterfind() 方法提供一个显式命名空间字典。这没有很好地记录:

    namespaces = {'eol': 'http://www.eol.org/transfer/content/0.3'} # add more as needed
    
    root.findall('eol:identifier', namespaces=namespaces)
    

    前缀在您传入的namespaces 参数中查找。这意味着您可以使用任何您喜欢的命名空间前缀; API 分离出 eol: 部分,在 namespaces 字典中查找相应的命名空间 URL,然后将搜索更改为查找 XPath 表达式 {http://www.eol.org/transfer/content/0.3}identifier

    如果你能切换到lxml library的话就更好了;该库支持相同的 ElementTree API,但在元素的 .nsmap 属性中为您收集命名空间。

    【讨论】:

      【解决方案2】:

      你有没有想过尝试beautifulsoup用python解析你的xml:

      http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Parsing%20XML

      有一些很好的文档和一个健康的在线小组,所以支持非常好

      一个

      【讨论】:

      • 我其实没有想到这一点。我会试试的。
      猜你喜欢
      • 1970-01-01
      • 2011-10-29
      • 2017-07-08
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      相关资源
      最近更新 更多