Weird characters after processing a xml file in an

2019-08-14 20:50发布

I am making an andorid applicaiton which loads data from a xml file. The problem is that the xml file is not processed correctly and I am not able to serialize it, because of that. I think the problem is related to the encoding of the file.

How I made the xml file? From Eclipse I have clicked on New-> File -> and created a blank xml, then I've filled it with the needed information.

Here is how the xml looks in the editor:

<?xml version="1.0" encoding="UTF-8"?>
<data>
<categories>
    <category value="Inbox"/>
    <category value="Private"/>
    <category value="Work"/>
    <category value="Business"/>
</categories>

<todos>
    <todo>
        <id>1</id>
        <text>Explore the app!</text>
    </todo>

    <todo>
        <id>2</id>
        <text>Add more todos!</text>
       <date>2013-05-09 12:21:55 CET</date>
   </todo>
</todos>
</data>

I am getting the xml file from res/xml and then I load the file in an Input Stream. After that I am converting the file to a String using the String constructor.

Here is the java code:

    InputStream is = getResources().openRawResource(R.xml.startingdata);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int next = is.read();
    while (next > -1) {
        bos.write(next);
        next = is.read();
    }
    bos.flush();
    byte[] result = bos.toByteArray();
    xmldata = new String(result,"UTF-8");

after this step, I show the new xmldata to a Toast, to check how it looks. However I receive part of the data, plus some weird characters. What I am doing wrong? Thank you in advance! I am attaching an image from my testing device, in order to show you the weird toast result:

enter image description here

1条回答
等我变得足够好
2楼-- · 2019-08-14 21:20

You need to set the encoding of your xml as UTF 8. You can do so by right clicking on your file and then set File Encoding from the drop down.

查看更多
登录 后发表回答