我的任务是将一些旧的XML解析代码重写为Python,我无意中遇到了joy,也就是cElementTree,我喜欢它,因为我可以在这么少的行中完成这么多工作。
我在xpath方面的经验并不广泛,这个问题更多的是关于进一步钻研结构的问题。
我在test.xml里有这个
<?xml version="1.0"?>
<ownershipDocument>
<issue>
<ic>0000030305</ic>
<iname>DUCOMM</iname>
<its>DCP</its>
</issue>
<ndt>
<ndtran>
<tc>
<tft>4</tft>
<tc>P</tc>
<esi>0</esi>
</tc>
</ndtran>
<ndtran>
<tc>
<tft>4</tft>
<tc>P</tc>
<esi>0</esi>
</tc>
</ndtran>
</ndt>
</ownershipDocument>我用Python编写了这个脚本:
import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print root.tag
print root.attrib
for child in root:
print(child.tag, child.attrib)
for issue in root.findall('issue'):
ic = issue.find('ic').text
iname= issue.find('iname').text
print(ic,iname)这给了我:
ownershipDocument
{}
('issue', {})
('ndt', {})
('0000030305', 'DUCOMM')这成功地获得了我在“问题”中需要的信息。
问题是我需要访问多个"ndtran“节点(在"ndt”节点中)。在解析时,我可以提取"tft“、"tc”和"esi“值作为组,但我需要遍历每个"tc”节点,提取"tft“、"tc”、"esi“值,然后将它们插入数据库,然后移动到下一个"tc”节点,然后再执行一次。
我试着迭代其中的每一个是这样的:
for tc in root.findall("./ndt/ndtran/tc"):
tft = tc.find('tft').text
tc = tc.find('tc').text
esi = tc.find('esi').text
print(tft,tc,esi)这几乎把我带到那里(我想),但它确实给了我一个错误。
esi = tc.find('esi').text
AttributeError: 'int' object has no attribute 'text'我希望这是有意义的。我相信我所追求的是DOM解析方法,这很好,因为这些文档并不大。
我很感激任何正确的建议和建议。
发布于 2017-03-29 02:14:04
在前面的行中,您将tc属性的值替换为string:
for tc in root.findall("./ndt/ndtran/tc"):
tft = tc.find('tft').text
tc = tc.find('tc').text
#^^ use different variable name here
esi = tc.find('esi').text
#^^ at this point, `tc` is no longer referencing the outer <tc> elements有趣的巧合是,string也有find()方法,在找不到关键字时返回int (-1),因此'int‘对象没有属性'text’错误。
https://stackoverflow.com/questions/43082887
复制相似问题