gpt4 book ai didi

java - 在android中的listview中加载本地xml数据

转载 作者:行者123 更新时间:2023-11-29 05:55:14 25 4
gpt4 key购买 nike

您能否推荐一个在 ListView 中加载本地 XML 数据的简单示例。

最佳答案

首先将您的 XML 文件放入原始文件夹,然后使用以下代码使用 Dom Parser 解析此 XML 文件。

public class XMLParsingDOMExample extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);

/** Create a new textview array to display the results */
TextView id[];
TextView imageurl[];

try {

InputStream is = res.openRawResource(R.raw.localxmlfileName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("item");

/** Assign textview array lenght by arraylist size */
id = new TextView[nodeList.getLength()];
imageurl = new TextView[nodeList.getLength()];

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

id[i] = new TextView(this);
imageurl[i] = new TextView(this);

Element fstElmnt = (Element) node;
NodeList idList = fstElmnt.getElementsByTagName("item_id");
Element idElement = (Element) idList.item(0);
idList = idElement.getChildNodes();
id[i].setText("id is = " + ((Node) idList.item(0)).getNodeValue());

NodeList imageurlList = fstElmnt.getElementsByTagName("item_image");
Element imageurlElement = (Element) imageurlList.item(0);
imageurlList = imageurlElement.getChildNodes();
imageurl[i].setText("imageurl is = " + ((Node) imageurlList.item(0)).getNodeValue());

layout.addView(id[i]);
layout.addView(imageurl[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}

/** Set the layout view to display */
setContentView(layout);
}
}

关于java - 在android中的listview中加载本地xml数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12435177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com