如何在Python中获取XML标记值

时间:2022-11-27 17:00:22

I have some XML in a unicode-string variable in Python as follows:

我在Python中的unicode-string变量中有一些XML,如下所示:

<?xml version='1.0' encoding='UTF-8'?>
<results preview='0'>
<meta>
<fieldOrder>
<field>count</field>
</fieldOrder>
</meta>
    <result offset='0'>
        <field k='count'>
            <value><text>6</text></value>
        </field>
    </result>
</results>

How do I extract the 6 in <value><text>6</text></value> using Python?

如何使用Python提取 6 中的6?

2 个解决方案

#1


3  

BeautifulSoup is the most simple way to parse XML as far as I know...

据我所知,BeautifulSoup是解析XML的最简单方法......

And assume that you have read the introduction, then just simply use:

并假设您已阅读介绍,然后只需使用:

soup = BeautifulSoup('your_XML_string')
print soup.find('text').string

#2


13  

With lxml:

使用lxml:

import lxml.etree
# xmlstr is your xml in a string
root = lxml.etree.fromstring(xmlstr)
textelem = root.find('result/field/value/text')
print textelem.text

Edit: But I imagine there could be more than one result...

编辑:但我想可能有不止一个结果......

import lxml.etree
# xmlstr is your xml in a string
root = lxml.etree.fromstring(xmlstr)
results = root.findall('result')
textnumbers = [r.find('field/value/text').text for r in results]

#1


3  

BeautifulSoup is the most simple way to parse XML as far as I know...

据我所知,BeautifulSoup是解析XML的最简单方法......

And assume that you have read the introduction, then just simply use:

并假设您已阅读介绍,然后只需使用:

soup = BeautifulSoup('your_XML_string')
print soup.find('text').string

#2


13  

With lxml:

使用lxml:

import lxml.etree
# xmlstr is your xml in a string
root = lxml.etree.fromstring(xmlstr)
textelem = root.find('result/field/value/text')
print textelem.text

Edit: But I imagine there could be more than one result...

编辑:但我想可能有不止一个结果......

import lxml.etree
# xmlstr is your xml in a string
root = lxml.etree.fromstring(xmlstr)
results = root.findall('result')
textnumbers = [r.find('field/value/text').text for r in results]