如何使用python解析xml文件,如果要退出,我试图在其中获取大于50的“得分”。在我的xml文件中,它确实存在,应该打印出65,93。
Test.xml
<analysis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<description/>
<alert url="/alert/224.xml" message="Hello"/>
<warning url="/warning/2.xml">
<score>65</score>
</warning>
<warning url="/warning/23.xml">
<score>33</score>
</warning>
<warning url="/warning/233.xml">
<score>93</score>
</warning>
<warning url="/warning/233.xml">
<score>93</score>
</warning>
</analysis>
答案 0 :(得分:1)
您可以使用BeautifulSoup
来解析xml
文件。然后,对于每个得分,我们可以将该得分添加到set
中,这意味着没有重复(也就是说,我们不会两次输出93
)。
import bs4
soup = bs4.BeautifulSoup(open('Test.xml'))
nums = set()
for score in soup.findAll('score'):
num = int(score.text)
if num > 50:
nums.add(num)
print(' '.join(str(n) for n in nums))
给出:
65 93
答案 1 :(得分:1)
使用BeautifulSoup
from bs4 import BeautifulSoup
score_set=set()
soup = BeautifulSoup(open('Test.xml'),"html.parser")
for score in soup.findAll('score'):
if (int(score.next_element)>50):
score_set.add(int(score.next_element))
print(score_set) # {65, 93}
答案 2 :(得分:1)
import xml.etree.ElementTree as ET
tree = ET.parse("Test.xml")
warnings = tree.findall("warning")
values = map(lambda x: x.getchildren()[0].text, warnings)
print ','.join(set(filter(lambda f: int(f)> 50, values)))