Search code examples
pythonxmlparsingxml-parsingminidom

How to parse XML in Python


I have an XML retrieved from NOAA and I am trying to parse it using minidom in Python, but I am not able to retrieve the values.

 `<parameters applicable-location="point1">
  <temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n7-1">
    <name>Daily Maximum Temperature</name>
    <value>75</value>
    <value>67</value>
    <value>65</value>
    <value>72</value>
    <value>65</value>
    <value>64</value>
    <value>62</value>
  </temperature>
</parameters>

`

I need to retrieve the values under tag maximum temperature.


Solution

  • Using the BeautifulpSoup is an easy way.

    You can try. like this.

    from bs4 import BeautifulSoup
    
    XML_STRING = """
    <parameters applicable-location="point1">
      <temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n7-1">
        <name>Daily Maximum Temperature</name>
        <value>75</value>
        <value>67</value>
        <value>65</value>
        <value>72</value>
        <value>65</value>
        <value>64</value>
        <value>62</value>
      </temperature>
    </parameters>
    """
    
    soup = BeautifulSoup(XML_STRING, 'html.parser')
    for tag in soup.find_all('value'):
        print(tag.string)