pythonxmldomnodevalue

python print text node value in xml element


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!


Solution

  • 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.)