2

I've an xml document on my project folder and i've problem with extraction of values of an attribute of an element.

My xml file looks like this :

<?xml version="1.0" ?>

<results filename="/home/maker/media/image" syncfile="/home/maker/media/synchro.xml">
    <readbit number="1" frame="10" bit="0" score="-0.483138" status="n" />
    <readbit number="2" frame="20" bit="1" score="0.416175" status="n" />
    <readbit number="3" frame="30" bit="0" score="-0.457450" status="n" />
    <readbit number="4" frame="40" bit="1" score="0.597008" status="y" />
    ....
</results>

What i tried in my view to get all values of the attribut bit:

def parse(request):
    xmldoc = minidom.parse('synchro.xml')
    readbitlist = xmldoc.getElementsByTagName('readbit')
    elements = []
    for s in readbitlist :
        x = s.attributes['bit'].value
        elements.append(x)
    return render(request, 'parse.html', {'elements': elements})

In my template:

<html>
<head>
  <title> Mark </title>
</head>
<body>
 {% for element in elements %}
 <p> {{ element }} </p>
 {% endfor %}
</body>
2
  • So what goes wrong? Do you get an error? If so, which one? Commented Jul 17, 2017 at 13:16
  • I don't get any error, I get an empty page. Commented Jul 17, 2017 at 13:20

2 Answers 2

2

The list values is empty becuse the populated list is elements, try this:

def parse(request):
    xmldoc = minidom.parse('synchro.xml')
    readbitlist = xmldoc.getElementsByTagName('readbit')
    values = []
    for s in readbitlist :
        x = s.attributes['bit'].value
        values.append(x)
    return render(request, 'parse.html', {'values': values})
Sign up to request clarification or add additional context in comments.

3 Comments

In my code it's correct, i just forget to replace values with elements while copying and writing my question. So it isn't working
I will delete the answer then.
Do you know if the xml file is found? the code should work. try using:import os from project.settings import BASE_DIR file_path = os.path.join(BASE_DIR, 'relative_path') or an absolute path.
1

I am parsing the XML files with The ElementTree XML API: https://docs.python.org/2/library/xml.etree.elementtree.html

It makes it very straightforward.

To parse the XML in your case:

import xml.etree.ElementTree as ET


def parse(request):
    xmldoc = minidom.parse('synchro.xml')
    root = xmldoc.getroot()
    elements = []
    for readbit in root.findall('readbit'):
        # get the attribute with value equal 'bit'
        bit = country.get('bit')
        elements.append(bit)
    return render(request, 'parse.html', {'elements': elements})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.