2017-05-02 41 views
0

我有一個從NOAA檢索到的XML,我試圖在Python中使用minidom解析它,但我無法檢索這些值。如何在Python中解析XML

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

`

我需要檢索標籤最高溫度下的數值。

+0

您可以將該示例修剪爲較小的測試集。但更重要的是,你需要發佈你已有的代碼。我們無法建議修復我們無法看到的代碼。 – tdelaney

+0

除了@tdelaney:閱讀[問]和[mcve]。 – boardrider

回答

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

更換python-devpython3-dev如果你使用python3。您可以按如下方式解析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