A
A
Alex Ivanov2019-03-25 16:00:43
Android
Alex Ivanov, 2019-03-25 16:00:43

How to select a specific element from an XML file?

There is an XML file voprosi.xml

<?xml version="1.0" encoding="utf-8"?>
    <questions>
    <question>
        <vopros>Сколько будет 2+2?</vopros>
        <otvet_1>2</otvet_1>
        <otvet_2>6</otvet_2>
        <otvet_3>8</otvet_3>
        <otvet_4  name="pravilno">4</otvet_4>
    </question>
    <question>
        <vopros>Сколько будет 3+3?</vopros>
        <otvet_1>12</otvet_1>
        <otvet_2>16</otvet_2>
        <otvet_3>18</otvet_3>
        <otvet_4  name="pravilno">6</otvet_4>
    </question>
    <question>
        <vopros>Сколько будет 4+4?</vopros>
        <otvet_1>22</otvet_1>
        <otvet_2>26</otvet_2>
        <otvet_3>18</otvet_3>
        <otvet_4  name="pravilno">8</otvet_4>
    </question>
    <question>
        <vopros>Сколько будет 5+5?</vopros>
        <otvet_1>2</otvet_1>
        <otvet_2>6</otvet_2>
        <otvet_3>8</otvet_3>
        <otvet_4  name="pravilno">10</otvet_4>
    </question>
</questions>

I need to display in the activity Question 3 and the answer options
Java code that receives data from the XML file
try {
            XmlPullParser parser = getResources().getXml(R.xml.voprosi);

            while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() == XmlPullParser.START_TAG
                        && parser.getName().equals("question")) {
                    
if(numvopr==3)
{

//....... тут надо вывести как-то вопрос и ответы 

 }
                  numvopr++;
                }
                parser.next();
            }


        } catch (Throwable t) {
            Toast.makeText(this,
                    "Ошибка при загрузке XML-документа: " + t.toString(),
                    Toast.LENGTH_LONG).show();
        }

Perhaps you can display the data so as not to parse the entire file, but only by the element number?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmtm, 2019-04-04
@Protossan

with a strong desire - you can, if you go to the block structure of the file,
i.e. when each tag <question>occupies strictly N bytes (the rest can be padded with spaces)
then the required block is found in one step: block number * N
but in a real project they will beat for this and not only on the hands -
there is a parser, there are objects, parsed - got the solution valuable for its predictability and ease of maintenance
PS: <otvet_1>12</otvet_1>it is better not to show view tags to anyone else,
like this it will be correct:

<question id="1" text="Сколько будет 4+4?" > - внесем вопрос в аттрибуты чтобы упростить парсинг
<item id="1" right="true">8</item>
<item id="2" >44</item>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question