使用Python和Django从文件中获取值时获取错误

时间:2017-06-16 10:36:48

标签: python xml django

我需要一些帮助。我试图以表格格式显示值,但使用Django和Python获得以下错误。错误如下所示。

  

raise SyntaxError("invalid predicate")

     

SyntaxError: invalid predicate

def search(request):
    per=[]
    if request.method == 'POST':
        rname=request.POST.get('rname')
        serch=request.POST.get('searchby')
        tree = ET.parse('roomlist.xml')
        root = tree.getroot()
        if serch==0:
           xyz = './/*[roomname='
           xyz = xyz + rname
           xyz= xyz + ']'
           result=root.findall(xyz)
           for x in result:
                  per.append({'roomname':x.find('roomname').text,'seat':x.find('noseats').text,'project':x.find('projectorscreen').text,'video':x.find('videoconf').text})
        return render(request,'booking/home.html',{'people': per}) 

我的观点部分如下。

  

home.html的:

{% if people %}
        <table>
            <tr>
                <th>Room Name</th>
                <th>seats</th>
                <th>Projector screen</th>
                <th>Video Conference</th>
            </tr>
        {% for person in people %}
            <tr>
                <td>{{person.roomname}}</td>
                <td>{{person.seat}}</td>
                <td>{{person.project}}</td>
                <td>{{person.video}}</td>
            </tr>
        {% endfor %}
        </table>
    {% else %}
        <p>No Record in the database</p>
    {% endif %}

我需要从下面的.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>

这里我需要从文件中搜索所有值并显示。请帮帮我。

1 个答案:

答案 0 :(得分:0)

看起来您正在使用xml模块来解析xmls。仅findall xml lxml模块仅from lxml import etree as ET

所以我的建议是改为使用if serch==0: xyz = './/room/roomname[text()="{}"]'.format(rname) result=root.xpath(xyz)

"\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""

然后:

replaceAll