Question

EDIT:

Thank you guys, I completely forgot the : at the end of the for statement. Also, for the original tags that I had with the spaces, I was just using that as filler text! The actual names do have aword_anotherword as element tags

Now if I have something like this,

<TIER name="a">
<tier_1> 
 <tier_2>
   <tier_3> a1</tier_3> 
 </tier_2>
</tier_1>

<tier_1> 
 <tier_2>
   <tier_3> a2</tier_3> 
 </tier_2>
</tier_1>

<tier_1> 
 <tier_2>
   <tier_3> a3</tier_3> 
 </tier_2>
</tier_1>
</TIER>

<TIER name="b">
<tier_1> 
 <tier_2>
   <tier_3> b1</tier_3> 
 </tier_2>
</tier_1>

<tier_1> 
 <tier_2>
   <tier_3> b2</tier_3> 
 </tier_2>
</tier_1>

<tier_1> 
 <tier_2>
   <tier_3> b3</tier_3> 
 </tier_2>
</tier_1>
</TIER>

How would I go abot printing just the tier_3 from the first tier with name="a" ?




I have an xml sheet something like this

<ALL TIERS>
<tier 1> 
 <tier 2>
   <tier 3> Hello one!</tier3> 
 </tier 2>
</tier 1>

<tier 1> 
 <tier 2>
   <tier 3> Hello two!</tier3> 
 </tier 2>
</tier 1>

<tier 1> 
 <tier 2>
   <tier 3> Hello three!</tier3> 
 </tier 2>
</tier 1>

</ALL TIERS>

I want to print allo f tier 3's text node values, using python so it turns ut like this

Hello one! Hello two! Hello three!

I wrote this:

from xml.dom import minidom 
xmldoc = minidom.parse(sys.argv[1])
xlist = xmldoc.getElementsByTagName('tier 3') 

for i in xlist

    print " ".join(t.nodeValue for t in i.childNodes if t.nodeType==t.TEXT_NODE)

but that gives me an error of invalid syntax pointing to "for i in xlist"

ccould someone help me correct this? Thank you!

Was it helpful?

Solution 2

Your immediate problem is that you're missing the : on the for statement

for i in xlist:

You're also going to want to import sys and your XML isn't well formed, maybe use <ALL_TIERS> instead of <ALL TIERS>? (You'd want to change the closing tags as well.)

OTHER TIPS

An alternative to get the text from you Xml.

Also your Xml isn't well formed as the tags have spaces in them.

import xml.etree.ElementTree as ET
txt = """<ALL-TIERS>
<tier-1>
 <tier-2>
   <tier-3> Hello one!</tier-3>
 </tier-2>
</tier-1>
<tier-1>
 <tier-2>
   <tier-3> Hello two!</tier-3>
 </tier-2>
</tier-1>
<tier-1>
 <tier-2>
   <tier-3> Hello three!</tier-3>
 </tier-2>
</tier-1>
</ALL-TIERS>
"""

root = ET.fromstring(txt)

for e in root.iter('ALL-TIERS'):
    print ">>"
    print ET.tostring(e, method="text").strip()
    print "<<"

for e in root.iter('tier-3'):
    print ">>"
    print ET.tostring(e, method="text").strip()
    print "<<"

Gives:

>>
Hello one!




    Hello two!




    Hello three!
<<
>>
Hello one!
<<
>>
Hello two!
<<
>>
Hello three!
<<
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top