【问题标题】:Parsing XML with cElementTree使用 cElementTree 解析 XML
【发布时间】:2017-03-29 01:52:02
【问题描述】:

我的任务是用 Python 重写一些旧的 XML 解析代码,我偶然发现了 cElementTree 的乐趣,我喜欢它,因为我可以用这么少的代码做很多事情。

我对@9​​87654322@ 的经验水平不是那么广泛,这个问题更多的是关于深入了解结构。

我有这个在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 解析方法,因为这些文档并没有那么大。

感谢任何正确方向的建议或指示。

【问题讨论】:

  • 尝试将 tcfor 更改为子项或与 tc iterfor child in root.findall("./ndt/ndtran/tc") 不同的名称

标签: python xml xpath celementtree


【解决方案1】:

您在上一行中将 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' 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多