2017-07-27 8 views
1

Pythonでrequestモジュールを使用して応答を得ています。応答はxmlの形式です。私はそれを解析し、各 'dt'タグの詳細を取得したい。私はlxmlを使ってそれを行うことができません。ここでxmlを使用してxmlをPythonで解析する(正しい方法が1つ)

は、XML応答である:

<?xml version="1.0" encoding="utf-8" ?> 
    <entry_list version="1.0"> 
     <entry id="harsh"> 
      <ew>harsh</ew><subj>MD-2</subj><hw>harsh</hw> 
      <sound><wav>harsh001.wav</wav><wpr>[email protected]</wpr></sound> 
      <pr>ˈhärsh</pr> 
      <fl>adjective</fl> 
      <et>Middle English <it>harsk,</it> of Scandinavian origin; akin to Norwegian <it>harsk</it> harsh</et> 
      <def> 
       <date>14th century</date> 
       <sn>1</sn> 
       <dt>:having a coarse uneven surface that is rough or unpleasant to the touch</dt> 
       <sn>2 a</sn> 
       <dt>:causing a disagreeable or painful sensory reaction :<sx>irritating</sx></dt> 
       <sn>b</sn> 
       <dt>:physically discomforting :<sx>painful</sx></dt> 
       <sn>3</sn> 
       <dt>:unduly exacting :<sx>severe</sx></dt> 
       <sn>4</sn> 
       <dt>:lacking in aesthetic appeal or refinement :<sx>crude</sx></dt> 
       <ss>rough</ss> 
      </def> 
      <uro><ure>harsh*ly</ure> <fl>adverb</fl></uro> 
      <uro><ure>harsh*ness</ure> <fl>noun</fl></uro> 
     </entry> 
    </entry_list> 

答えて

1

簡単な方法は、XML文書の階層を下にトラバースするだろう。

import requests 
from lxml import etree 

re = requests.get(url) 
root = etree.fromstring(re.content) 
print(root.xpath('//entry_list/entry/def/dt/text()')) 

これは、XML文書の各「dt」タグのテキスト値を与えます。

0
from xml.dom import minidom 

# List with dt values 
dt_elems = [] 

# Process xml getting elements by tag name 
xmldoc = minidom.parse('text.xml') 
itemlist = xmldoc.getElementsByTagName('dt') 

# Get the values 
for i in itemlist: 
    dt_elems.append(" ".join(t.nodeValue for t in i.childNodes if t.nodeType==t.TEXT_NODE)) 

# Print the list result 
print dt_elems 
関連する問題