使用Python解析XML

时间:2011-04-12 13:31:17

标签: xml elementtree

我正在使用Python 2.5和WinXP。 我正在解析xml文件,如下所示:

<Test>
<Default_Config>
  <LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}</LINK> 
  <Lanestat>{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}</Lanestat> 
  </Default_Config>
  </Test>

然而,当我打印输出时,输出如下:

(None, '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')

问题:如何修改我的代码,以便出现Link和Lanestat而不是None。 TQ 代码:

import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()


for elem in doc.findall('Default_Config/LINK'):
    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):

    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

2 个答案:

答案 0 :(得分:1)

import xml.etree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    a = elem.tag, elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):
    a = elem.tag, elem.text
    print a

=&GT;

('LINK', '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
('Lanestat', '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')

答案 1 :(得分:0)

尝试使用a = elem.tag而不是a = elem.get('LINK')

import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    a=elem.tag, elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):
    a=elem.tag, elem.text
    print a