我对 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>
您的 XML 文件使用默认命名空间。您需要使用正确的命名空间来限定您的搜索:
identifier = node.findtext('{http://www.eol.org/transfer/content/0.3}identifier')
让 ElementTree 匹配正确的元素。
您还可以给.find()
, findall()
and iterfind()
方法是显式命名空间字典。这没有很好的记录:
namespaces = {'eol': 'http://www.eol.org/transfer/content/0.3'} # add more as needed
root.findall('eol:identifier', namespaces=namespaces)
前缀是only抬头望去namespaces
您传入的参数。这意味着您可以使用任何您喜欢的命名空间前缀; API 分离了eol:
部分,在中查找相应的命名空间 URLnamespaces
字典,然后更改搜索以查找 XPath 表达式{http://www.eol.org/transfer/content/0.3}identifier
反而。
如果您可以切换到lxml library事情变得更好了;该库支持相同的 ElementTree API,但会在.nsmap
元素上的属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)