【发布时间】:2018-04-10 09:17:32
【问题描述】:
简介
我有一个汇总的“country.xml”文件,如下所示,我从一个网站获得 我需要通过它的属性名称来解析这个 xml。
比如我想要这样一个列表:
Country: Germany
Population: 82521653
GDP: 3466000000000
Country: Switzerland
Population: 8417700
GDP: 659800000000
问题是,标签名称几乎相同。
我现在所拥有的
Country: Germany
Population: Germany
GDP: Germany
Country: Switzerland
Population: Switzerland
GDP: Switzerland
Country: Austria
Population: Austria
GDP: Austria
MainActivity.java
public class MainActivity extends Activity {
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("country.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("Country");
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\nCountry : " + getValue("string", element2)+"\n");
tv1.setText(tv1.getText()+"Population : " + getValue("string", element2)+"\n");
tv1.setText(tv1.getText()+"GDP : " + getValue("string", element2)+"\n");
tv1.setText(tv1.getText()+"-----------------------");
}
}
} catch (Exception e) {e.printStackTrace();}
}
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
}
Country.xml
<Country>
<string name="CountryName">Germany</string>
<string name="Population">82521653</string>
<null name="Area">357385</null>
<null name="GDP">3466000000000</null>
</Country>
<Country>
<string name="CountryName">Switzerland</string>
<string name="Population">8417700</string>
<null name="Area">41285</null>
<null name="GDP">659800000000</null>
</Country>
<Country>
<string name="CountryName">Austria</string>
<string name="Population">8772865</string>
<null name="Area">83878</null>
<null name="GDP">386700000000</null>
</Country>
问题
如何通过属性名称获取值?
我尝试的是:
tv1.setText(tv1.getText()+"\nCountry : " + getValue("string name=\"CountryName\"", element2)+"\n");
但这给了我一个空字符串。
【问题讨论】:
-
您在所有 getValue() 调用中都使用相同的标记(“字符串”)。会不会是这个问题?
-
是的,我想是的。但是标签(“字符串”)也在 xml 文件的几行中。当我将调用的值更改为 "string name=\"CountryName\"" 时,它会给我一个空结果。
标签: android xml xml-parsing nodelist