Я хочу получить тег внутри массива xml, например country
, countryCode
, iso2
, iso3
.
<?xml version = "1.0" encoding = "utf-8"?>
<resources>
<string-array name = "country_data">
<item>
<country>Afghanistan</country>
<countryCode>93</countryCode>
<iso2>AF</iso2>
<iso3>AFG</iso3>
</item>
<item>
<country>Albania</country>
<countryCode>355</countryCode>
<iso2>AL</iso2>
<iso3>ALB</iso3>
</item>
<item>
<country>Algeria</country>
<countryCode>213</countryCode>
<iso2>DZ</iso2>
<iso3>DZA</iso3>
</item>
<item>
<country>American Samoa</country>
<countryCode>1-684</countryCode>
<iso2>AS</iso2>
<iso3>ASM</iso3>
</item>
<item>
<country>Andorra</country>
<countryCode>376</countryCode>
<iso2>AD</iso2>
<iso3>AND</iso3>
</item>
<item>
<country>Angola</country>
<countryCode>244</countryCode>
<iso2>AO</iso2>
<iso3>AGO</iso3>
</item>
</string-array>
</resources>
Я хочу получить country
, countryCode
, iso2
и iso3
независимо друг от друга в разные ArrayList (страна ArrayList, код страны, iso2, iso3).
Чтобы получить доступ к string-array
, вы можете сделать это:
String[] ar = getResources().getStringhArray(R.array.country_data);
Однако массив представляет собой одномерный массив. Итак, такой тост
Toast.makeText(this, ar[0], Toast.Length_SHORT).show();
покажет
Afghanistan 93 AF AFG
Затем вы можете разделить строку, если уверены, что в названиях стран не будет вставлено пробелов.
Если xml
является внешним файлом, то гораздо лучше использовать XmlPullParserFactory
для анализа файла. В этом случае вы можете получить доступ к стране, коду страны, iso2, iso3 напрямую.
Вы имеете в виду пример XmlPullParserFactory
или для разделения строки?
я выложил свое решение
This is how I did it.
I used XmlPullParserFactory to get the tags from an xml file in the assets folder.
..
События XmlPullParser
Метод следующий() класса XMLPullParser перемещает указатель курсора на следующее событие. Как правило, мы используем четыре константы (работает как событие), определенные в интерфейсе XMLPullParser. Эти:
START_TAG
: Был прочитан начальный тег XML.
TEXT
: текстовый контент был прочитан; текстовое содержимое можно получить с помощью метода getText().
END_TAG
: Конечный тег был прочитан.
END_DOCUMENT
: Больше событий нет.
..
Разбор XML в Android XMLPullParser
XMLPullParser
проверит XML-файл с рядом событий, таких как перечисленные выше, для анализа XML-документа.
Чтобы читать и анализировать данные XML с помощью XMLPullParser в Android, нам нужно создать экземпляр объектов XMLPullParserFactory, XMLPullParser в приложениях Android.
Ниже приведен мой код для чтения и анализа данных XML с использованием XMLPullParser в приложениях для Android с XMLPullParserFactory, XMLPullParser и серией событий для получения необходимой информации из объектов XML.
Затем данные передаются в BaseAdapter.
package com.f.countryarraytest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private ListView listView;
public TextView tvCountryName, tvCountryCode, tvCountryIso2;
private CustomAdapter customAdapter;
private static final String tagCountryItem = "country";
private static final String tagCountryName = "countryName";
private static final String tagCountryCode = "countryCode";
private static final String tagCountryIso2 = "countryIso2";
private static final String tagCountryIso3 = "countryIso3";
private ArrayList<String> countryName, countryCode, countryIso2, countryIso3;
private ArrayList<HashMap<String, String>> countryListArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
tvCountryName = findViewById(R.id.tvMainActivity_CountryName);
tvCountryCode = findViewById(R.id.tvMainActivity_CountryCode);
tvCountryIso2 = findViewById(R.id.tvMainActivity_CountryIso2);
countryName = new ArrayList<>();
countryCode = new ArrayList<>();
countryIso2 = new ArrayList<>();
countryIso3 = new ArrayList<>();
try{
countryListArray = new ArrayList<>();
HashMap<String,String> country = new HashMap<>();
InputStream inputStream = getAssets().open("countries.xml");
XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
XmlPullParser parser = parserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false);
parser.setInput(inputStream,null);
String tag = "" , text = "";
int event = parser.getEventType();
while (event!= XmlPullParser.END_DOCUMENT){
tag = parser.getName();
switch (event){
case XmlPullParser.START_TAG:
if (tag.equals(tagCountryItem))
country = new HashMap<>();
break;
case XmlPullParser.TEXT:
text=parser.getText();
break;
case XmlPullParser.END_TAG:
if (tag.equalsIgnoreCase(tagCountryName)){
country.put(tagCountryName,text);
} else if (tag.equalsIgnoreCase(tagCountryCode)){
country.put(tagCountryCode,text);
} else if (tag.equalsIgnoreCase(tagCountryIso2)){
country.put(tagCountryIso2,text);
} else if (tag.equalsIgnoreCase(tagCountryIso3)){
country.put(tagCountryIso3,text);
} else if (tag.equalsIgnoreCase(tagCountryItem)){
if (country != null){
countryListArray.add(country);
}
}
/*switch (tag){
case tagCountryName: country.put(tagCountryName,text);
break;
case tagCountryCode: country.put(tagCountryCode,text);
break;
case tagCountryIso2: country.put(tagCountryIso2,text);
break;
case tagCountryIso3: country.put(tagCountryIso3,text);
break;
case tagCountryItem:
if (country != null){
countryListArray.add(country);}
break;
}*/
break;
}
event = parser.next();
}
//Get ArrayList With County Data HashMap
getHashMapData();
customAdapter = new CustomAdapter(this, countryName, countryCode, countryIso2, countryIso3);
listView.setAdapter(customAdapter);
}
catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
private void getHashMapData(){
countryName.clear();
countryCode.clear();
countryIso2.clear();
countryIso3.clear();
try {
if (countryListArray.size() > 0) {
for (int i = 0; i < countryListArray.size(); i++) {
HashMap<String, String> hashmap = countryListArray.get(i);
countryName.add(hashmap.get(tagCountryName));
countryCode.add(hashmap.get(tagCountryCode));
countryIso2.add(hashmap.get(tagCountryIso2));
countryIso3.add(hashmap.get(tagCountryIso3));
}
}
} catch (Exception e){}
}
}
Here is the code for my BaseAdapter.
package com.f.countryarraytest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> countryName, countryCode, countryIso2, countryIso3;
private LayoutInflater layoutInflater;
private TextView tvSelectedCountryName, tvSelectedCountryCode, tvSelectedCountryIso2;
public CustomAdapter(MainActivity mainActivity, ArrayList<String> countryName, ArrayList<String> countryCode, ArrayList<String> countryIso2, ArrayList<String> countryIso3){
this.context = mainActivity.getApplicationContext();
this.countryName = countryName;
this.countryCode = countryCode;
this.countryIso2 = countryIso2;
this.countryIso3 = countryIso3;
this.layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.tvSelectedCountryName = mainActivity.tvCountryName;
this.tvSelectedCountryCode = mainActivity.tvCountryCode;
this.tvSelectedCountryIso2 = mainActivity.tvCountryIso2;
}
@Override
public int getCount() {
return countryName.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = layoutInflater.inflate(R.layout.custom_listview_country_picker, null);
}
LinearLayout llItem;
final TextView tvCountryName, tvCountryCode, tvCountryIso2;
llItem = convertView.findViewById(R.id.llCountryPicker);
tvCountryName = convertView.findViewById(R.id.tvCountryName);
tvCountryCode = convertView.findViewById(R.id.tvCountryCode);
tvCountryIso2 = convertView.findViewById(R.id.tvCountryIso2);
//Set Values
tvCountryName.setText(countryName.get(position));
tvCountryCode.setText(String.valueOf(countryCode.get(position)));
tvCountryIso2.setText(countryIso2.get(position));
llItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvSelectedCountryName.setText(tvCountryName.getText().toString().trim());
tvSelectedCountryCode.setText(tvCountryCode.getText().toString().trim());
tvSelectedCountryIso2.setText(tvCountryIso2.getText().toString().trim());
}
});
return convertView;
}
}
Here is the xml layout for the list item.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:background = "#ffffff"
android:orientation = "horizontal">
<LinearLayout
android:layout_width = "match_parent"
android:orientation = "horizontal"
android:id = "@+id/llCountryPicker"
android:gravity = "center_vertical"
android:layout_height = "wrap_content">
<!--Country Flag-->
<ImageView
android:layout_width = "28dp"
android:padding = "2dp"
android:contentDescription = "countryFlag"
android:src = "@android:drawable/ic_menu_gallery"
android:id = "@+id/ivCountryPicker_CountryFlag"
android:layout_marginStart = "10dp"
android:layout_height = "28dp"
/>
<!-- Country Code And Name -->
<LinearLayout
android:layout_width = "match_parent"
android:orientation = "vertical"
android:layout_marginTop = "5dp"
android:layout_height = "wrap_content">
<LinearLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal">
<TextView
android:id = "@+id/tvCountryIso2"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginStart = "10dp"
android:singleLine = "true"
android:textColorHint = "#000"
android:layout_marginEnd = "10dp"
android:hint = "Iso2"
android:textColor = "#000000"
android:textSize = "14dp"
/>
<TextView
android:id = "@+id/tvCountryName"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:singleLine = "true"
android:textColorHint = "#000"
android:layout_marginEnd = "10dp"
android:hint = "country Name"
android:textColor = "#000000"
android:textSize = "14dp"
/>
</LinearLayout>
<TextView
android:id = "@+id/tvCountryCode"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginStart = "10dp"
android:singleLine = "true"
android:minEms = "3"
android:textColorHint = "#000"
android:maxEms = "5"
android:layout_marginEnd = "10dp"
android:hint = "000"
android:textColor = "#000000"
android:textSize = "14dp"
/>
</LinearLayout>
</LinearLayout>
Здорово! XmlPullParserFactory
— очень полезная библиотека.
Кто-нибудь с идеей?