簡體   English   中英

使用InputStream在Android中打開XML文件

[英]Opening XML file in Android with inputstream

我在res / xml / products.xml中有一個名為products.xml的文件,其中包含以下XML數據:

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>     
        <productname>Jeans</productname>
        <productcolor>red</productcolor>
        <productquantity>5</productquantity>
    </product>
    <product>     
        <productname>Tshirt</productname>
        <productcolor>blue</productcolor>
        <productquantity>3</productquantity>
    </product>
    <product>     
        <productname>shorts</productname>
        <productcolor>green</productcolor>
        <productquantity>4</productquantity>
    </product>
</products>

我的主要目標是使用XMLPullParser對其進行解析。 但是,當我嘗試打開文件時,得到的輸出很奇怪。 這是我正在使用的代碼:

    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(appContext
                .getResources().openRawResource(R.xml.products), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    }

    StringBuilder s = new StringBuilder();
    String line;
    while ((line = in.readLine()) != null) {
        s.append(line);
    }

    System.out.println("String: " + s);

而且我得到了一個奇怪的輸出,其中包含以下這些字符:

�������������������������������������������������������������������

我究竟做錯了什么? 謝謝

您必須將XML文件放入res / raw文件夾,然后使用openRawResource(R.raw.products)進行讀取,或者,如果要將其解析為XML,請使用getResources().getXml(id) ,但是會得到XmlResourceParser而不是String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM