Extracting XML Tag Names

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Elfers
    New Member
    • Aug 2010
    • 9

    Extracting XML Tag Names

    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.

    Code:
     
    <Forecast>
     <Config/>
     <Date>THU SEP 9 2010</Date>
     <Time>4:53 PM CDT</Time>
    <Thursday>
     <Conditions>Partly Cloudy</Conditions>
     <Description>Partly cloudy</Description>
     <Image>http://www.</Image>
     <High>68°F</High>
     <Low>50°F</Low>
     <Pop>0</Pop>
     </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,

    Code:
     
    forecast_node = doc.getElementsByTagName('Forecast')
    current_day = forecast_node[0].childNodes[4].tagName
    but it seems that I cannot use tagName in this manner. Any suggestions for me?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    It seems that you want the fourth child element node of the Forecast node. To get that, you must skip the text nodes. Example:
    Code:
    xmlDoc = minidom.parseString(xmlStr)
    forecast_node = xmlDoc.getElementsByTagName('Forecast')
    
    # get 4th element node
    count = 0
    for child in forecast_node[0].childNodes:
        if child.nodeType == 1:
            count += 1
            if count == 4:
                break
    print child

    Comment

    • Dave Elfers
      New Member
      • Aug 2010
      • 9

      #3
      Thanks for pointing me this way, I am very new to this and never would have thought of it. Had to to change to
      Code:
      print child.toxml
      to get the tag name completely out of the dom element. Thanks again!

      Comment

      Working...