如何在Python中解析XML

时间:2017-05-02 04:16:27

标签: python xml parsing xml-parsing minidom

我有从NOAA检索到的XML,我试图在Python中使用minidom解析它,但我无法检索值。

 `<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>

`

我需要检索标签最高温度下的值。

2 个答案:

答案 0 :(得分:3)

使用BeautifulpSoup是一种简单的方法。

你可以试试。像这样。

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)

答案 1 :(得分:2)

您可以将Beautiful Soup与libxml一起使用。以下是如何为ubuntu 14.04测试正确的设置:

sudo apt-get install libxml2-dev libxslt1-dev lib32z1-dev python-dev -y
pip install lxml
pip install beautifulsoup4

如果您使用的是python3,请将python-dev替换为python3-dev。您可以按如下方式解析xml:

file_content = """your xml string here"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(file_content, "xml")
max_temp_list = [int(item.string) for item in soup.find("temperature", {"type": "maximum"}).findAll("value")]
print(max_temp_list)

有关查找元素的更多示例,请参阅documentation

相关问题