0

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

2 Answers 2

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

=>

('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}')
Sign up to request clarification or add additional context in comments.

2 Comments

now i want to extract info from lanestat 1 to obtain a 2. however, this is a tuple. i manage to do it using below code: for elem in doc.findall('Default_Config/Lanestat'): a=elem.tag, elem.text print a print type(a) b=a[1] print type(b) c=eval(b) print type(c) print c[1]. is there any elegant way of doing this? tq
@maximus: ask a new question, and I'm sure someone will come to the rescue!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.