2017-06-16 41 views
0

我需要根据用户输入使用python搜索XML表单中的值,但是它会给出空白值。我在下面解释我的代码。无法使用Python从XML文件中获取搜索值

import xml.etree.ElementTree as ET 
tree = ET.parse('roomlist.xml') 
root = tree.getroot() 
print(root.findall(".//*[@roomname=\"cottage\"]")) 

我的XML文件如下。

<?xml version="1.0" ?><roomlist> 
    <location name="Bangalore"> 
    <room id="1uy92j908u092"> 
     <roomname> Aquarius </roomname> 
     <noseats> 10 </noseats> 
     <projectorscreen>yes</projectorscreen> 
     <videoconf>yes</videoconf> 
    </room> 
    </location> 
<location name="Bhubaneswar"><room id="131198912460"><roomname>cottage</roomname><noseats>5</noseats><projectorscreen>Yes</projectorscreen><videoconf>Yes</videoconf></room></location><location name="puri"><room id="509955554930"><roomname>room1</roomname><noseats>10</noseats><projectorscreen>No</projectorscreen><videoconf>Yes</videoconf></room></location></roomlist> 

这里没有数据来。在这里,我需要搜索所有数据后应推入一个数组。

+0

显示预期结果 – RomanPerekhrest

+0

'$ result = [{'lname':'Bhubaneswar','rname':'cottage','noseats':5,'projectorscreen':是,'video':'yes'}]' – satya

+0

@RomanPerekhrest:My预期产出应该高于预期。 – satya

回答

0

您可以遍历象下面这样在你的XML值:

for roomname in root.iter('roomname'): 
    print(roomname.text) 

这样你就可以检查它是否有太多

for roomname in root.iter('roomname'): 
    if roomname.text == 'cottage': 
     print(roomname.text) 

追加名列表:

lst = [] 
for roomname in root.iter('roomname'): 
    lst.append(roomname.text) 

在你的情况下,你需要深入遍历树。下面将进入房间节点的属性

for child in root: 
    for attr in child.find('room'): 
     print(attr) 

将输出

<Element 'roomname' at 0x7f9c064d5090> 
<Element 'noseats' at 0x7f9c064d50d0> 
<Element 'projectorscreen' at 0x7f9c064d5150> 
<Element 'videoconf' at 0x7f9c064d5190> 
<Element 'roomname' at 0x7f9c064d5250> 
<Element 'noseats' at 0x7f9c064d5290> 
<Element 'projectorscreen' at 0x7f9c064d52d0> 
<Element 'videoconf' at 0x7f9c064d5310> 
<Element 'roomname' at 0x7f9c064d53d0> 
<Element 'noseats' at 0x7f9c064d5410> 
<Element 'projectorscreen' at 0x7f9c064d5450> 
<Element 'videoconf' at 0x7f9c064d5490> 

可以使用的.text的元素创建字典或者列出你需要

另外:https://docs.python.org/3/library/xml.etree.elementtree.html

祝你好运

+0

在这种情况下,只有一个值即将到来。 – satya

+0

这里我需要所有的价值。 – satya

+0

你究竟需要你的代码做什么?上面的第一个循环将打印所有房间名称,如果这是您需要的,则可以使用相同的循环结构将名称追加到列表中。也请参考文档,也许在一定程度上澄清你的问题。 – Maarten