首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用xlml在Python中解析xml (一种正确的方法

使用xlml在Python中解析xml (一种正确的方法
EN

Stack Overflow用户
提问于 2017-07-27 18:08:13
回答 2查看 354关注 0票数 1

我使用Python中的requests模块得到一个响应,该响应是xml格式的。我想要解析它,并从每个'dt‘标签中获取详细信息。我不能使用lxml做到这一点。

下面是xml响应:

代码语言:javascript
复制
<?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>!h@rsh</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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-27 18:08:13

一种简单的方法是向下遍历xml文档的层次结构。

代码语言:javascript
复制
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‘标记提供文本值。

票数 1
EN

Stack Overflow用户

发布于 2017-07-27 20:13:52

代码语言:javascript
复制
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  
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45347641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档