从资源的 android 字符串数组中获取数据

Get data from android string array from resource

我知道如何从 string-array 获取数据。我已经这样做了。

<string-array name="values">
   <item>value1</item>
   <item>value2</item>
</string-array>

String[] values = this.getResources().getStringArray(R.array.values);

但我不知道下面的类型 string-array 是否可行并且难以从中获取值。

<string-array name="country_data">
        <item>
            <country>Afghanistan</country>
            <countryCode>93</countryCode>
            <iso2>AF</iso2>
            <iso3>AFG</iso3>
        </item>
    </string-array>

如果可能请帮我获取值。

当然可以。

总结:

  1. 定义代表您的模型的 POJO
  2. 创建函数以将数组的字符串数组从资源导入到此 POJO

请记住,您不能使用自定义 xml 条目,它们必须是 <item>。你需要预先知道它的类型。

xml :

<string-array name="_name">
        <item>n11</item>
        <item>n12</item>
        <item>n13</item>
        <item>n14</item>
        <item>n15</item>
        <item>n16</item>
    </string-array>

检索于 java class:

   String[] test;
test = getResources().getStringArray(R.array._name); 

I dont know whether the below type string-array is possible

不是。

如果您想要任意 XML,请使用 res/xml/ 作为您喜欢的任何 XML 结构。然后,您可以使用 getResources().getXml() 获得一个 XmlPullParser,您可以使用它来解析 XML.

或者,将每个 <item> 元素的内容包装在 CDATA 中,这样可以防止资源解析器弄乱它们。然后,您从数组中检索到的每个字符串都是纯文本 XML,您需要对其进行解析。

或者,在 res/raw/assets/ 中使用 JSON,使用您最喜欢的 JSON 解析器(例如 Gson)。

或者,use SQLiteAssetHelper在您的应用程序中打包一个预加载了此数据的数据库。

或者,使用 R. Zagórski's solution,每个对象有一个 <string-array>,对象的每个字段有 <item> 个元素。