我是 android 开发新手,我想使用 Dom Parser 解析一个特定的 xml 文件。xml 结构是这样的。
<Images>
<image link="a.tgcdn.net/images/products/zoom/e554_android_plush_robot.jpg"/>
<image link="a.tgcdn.net/images/products/zoom/e554_android_plush_robot.jpg"/>
<image link="http://cdn.androidpolice.com/wp-content/themes/ap1/images/android1.png"/>
<image link="http://cdn.androidpolice.com/wp-content/themes/ap1/images/android1.png"/>
<image link="http://cdn.androidpolice.com/wp-content/themes/ap1/images/android1.png"/>
</Images>
我想将这些 Web 链接添加到数组列表中。建议我解决它..甚至与此相关的任何链接或教程都会有所帮助。谢谢。
这是完整的代码..
public class MainActivity extends Activity {
String xmlurl = "--url of xml---";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> mImageLink = new ArrayList<String>();
try {
URL url = new URL(xmlurl);
XMLParser parser = new XMLParser();
String xml = parser.getXMLfromUrl(url);
Document doc = parser.getDomElement(xml);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc1 = db.parse(new InputSource(url.openStream()));
doc1.getDocumentElement().normalize();
NodeList nodeList = doc1.getElementsByTagName("photo");
for (int i = 0; i < nodeList.getLength(); i++) {
Element websiteElement = (Element) nodeList.item(i);
nodeList = websiteElement.getChildNodes();
mImageLink.add(websiteElement.getAttribute("link"));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
for(int i=0;i<mImageLink.size();i++){
Log.d("Photo link --- " + i,mImageLink.get(i));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}