By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,767 Members | 1,987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,767 IT Pros & Developers. It's quick & easy.

Extracting XML Tag Names

P: 9
Hello, I need to get the tag name from an XML file. I know where it is going to be everytime, but I do not know what the name will be. This is a snippet of my xml data.

Expand|Select|Wrap|Line Numbers
  2. <Forecast>
  3.  <Config/>
  4.  <Date>THU SEP 9 2010</Date>
  5.  <Time>4:53 PM CDT</Time>
  6. <Thursday>
  7.  <Conditions>Partly Cloudy</Conditions>
  8.  <Description>Partly cloudy</Description>
  9.  <Image>http://www.</Image>
  10.  <High>68F</High>
  11.  <Low>50F</Low>
  12.  <Pop>0</Pop>
  13.  </Thursday> 
I need to extract 'Thursday' from the tag to know what day the weather data is for. Tomorrow it will be Friday and so on and so forth. It will always be in the same place. I have tried this,

Expand|Select|Wrap|Line Numbers
  2. forecast_node = doc.getElementsByTagName('Forecast')
  3. current_day = forecast_node[0].childNodes[4].tagName 
but it seems that I cannot use tagName in this manner. Any suggestions for me?
Sep 9 '10 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 2.5K+
P: 2,851
It seems that you want the fourth child element node of the Forecast node. To get that, you must skip the text nodes. Example:
Expand|Select|Wrap|Line Numbers
  1. xmlDoc = minidom.parseString(xmlStr)
  2. forecast_node = xmlDoc.getElementsByTagName('Forecast')
  4. # get 4th element node
  5. count = 0
  6. for child in forecast_node[0].childNodes:
  7.     if child.nodeType == 1:
  8.         count += 1
  9.         if count == 4:
  10.             break
  11. print child
Sep 10 '10 #2

P: 9
Thanks for pointing me this way, I am very new to this and never would have thought of it. Had to to change to
Expand|Select|Wrap|Line Numbers
  1. print child.toxml
to get the tag name completely out of the dom element. Thanks again!
Sep 10 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.