我在解析以下 XML 时遇到问题:
<key>key 1</key>
<string>string 1</string>
<key>key 2</key>
<string>string 2</string>
<key>key 3</key>
<string>string 3</string>
我写了下面的代码,但是我只得到了TextView中第一个标签的数据,没有得到标签string2和string 3的数据。如何解析同名标签的XML?
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context mContext = this;
TextView tv = (TextView) findViewById(R.id.info);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
AssetManager assetManager = mContext.getAssets();
InputStream inputStream = assetManager.open("abc.xml");
Document doc=db.parse(inputStream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("string");
for (int i = 0; i < nodeList.getLength(); i++) {
tv.setText( "\n\n"+ nodeList.item(i).getChildNodes().item(i).getNodeValue()+"\n");
}
} catch (Exception e) {
System.out.println("Pasing Excpetion = " + e);
}
}
最佳答案
可能是您从这种情况开始...改变您的情况...
for (int i = 0; i < nodeList.getLength(); i++) {
为了...
for (int i = 0; i < nodeList.getLength()-1; i++) {
更新:
改变这个....
tv.setText( "\n\n"+ nodeList.item(i).getChildNodes().item(i).getNodeValue()+"\n");
为了...
tv.setText( "\n\n"+ nodeList.item(i).getChildNodes().item(0).getNodeValue()+"\n");
关于android - 解析具有相同名称标签的 XML 在 Android 中给出 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22076722/