开发者

Parsing XML Using Python

i'm using Python 2.5 and WinXP. i am parsing xml file as below:

<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>

however when i print out, the output is as below:

(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}')

Question: How to modify my code so that Link and Lanestat appears instead of None. tq Code:

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


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

=>

('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}')


try using a=elem.tag instead of 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜