首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用cElementTree解析XML

用cElementTree解析XML
EN

Stack Overflow用户
提问于 2017-03-29 01:52:02
回答 1查看 246关注 0票数 1

我的任务是将一些旧的XML解析代码重写为Python,我无意中遇到了joy,也就是cElementTree,我喜欢它,因为我可以在这么少的行中完成这么多工作。

我在xpath方面的经验并不广泛,这个问题更多的是关于进一步钻研结构的问题。

我在test.xml里有这个

代码语言:javascript
复制
<?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编写了这个脚本:

代码语言:javascript
复制
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)

这给了我:

代码语言:javascript
复制
ownershipDocument
{}
('issue', {})
('ndt', {})
('0000030305', 'DUCOMM')

这成功地获得了我在“问题”中需要的信息。

问题是我需要访问多个"ndtran“节点(在"ndt”节点中)。在解析时,我可以提取"tft“、"tc”和"esi“值作为组,但我需要遍历每个"tc”节点,提取"tft“、"tc”、"esi“值,然后将它们插入数据库,然后移动到下一个"tc”节点,然后再执行一次。

我试着迭代其中的每一个是这样的:

代码语言:javascript
复制
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)

这几乎把我带到那里(我想),但它确实给了我一个错误。

代码语言:javascript
复制
esi = tc.find('esi').text
AttributeError: 'int' object has no attribute 'text'

我希望这是有意义的。我相信我所追求的是DOM解析方法,这很好,因为这些文档并不大。

我很感激任何正确的建议和建议。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-29 02:14:04

在前面的行中,您将tc属性的值替换为string

代码语言:javascript
复制
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’错误。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43082887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档