——- android培训、java培训、期待与您交流! ———-
简单的xml解析实例,刚写完的,分享给刚接触xml的童鞋们!
/**
* 用DOM树的方式对xml进行解析
* 对xml进行解析
*
*/
public class Test {
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
try {
//得到DOM解析器工厂实例
DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();
//从DOM工厂中获得DOM解析器
DocumentBuilder b = a.newDocumentBuilder();
//解析XML文档,得到一个Document,即DOM树
Document c = b.parse("src/信息收藏.xml");
//读取新闻
NodeList d = c.getElementsByTagName("item");
for(int i=0;i<d.getLength();i++){
Node node = d.item(i);
Element e = (Element)node;
String s= e.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
String s3= e.getElementsByTagName("pubDate").item(0).getFirstChild().getNodeValue();
System.out.println((i+1)+"\t"+s3+"\t"+s);
}
} catch (Exception e) {
}
new Test().run();
}
//查询一条信息,按<item>标签查找
public void run(){
//得到DOM解析器工厂实例
try {DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();
//从DOM工厂中获得DOM解析器
DocumentBuilder b = a.newDocumentBuilder();
//解析XML文档,得到一个Document,即DOM树
Document c = b.parse("src/信息收藏.xml");
//读取新闻
NodeList d = c.getElementsByTagName("item");
System.out.print("输入:");
int num =input.nextInt();
Node node = d.item(num-1);
Element e = (Element)node;
String s= e.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
String s3= e.getElementsByTagName("pubDate").item(0).getFirstChild().getNodeValue();
System.out.println((num)+"\t"+s3+"\t"+s);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
<?xml version="1.0" encoding="GBK"?>
<channel>
<item>
<title><![CDATA[超高性价比智能机 华为 U8650 仅1280元]]></title>
<pubDate>2014-11-25 12:50:46</pubDate>
</item>
<item>
<title><![CDATA[双512MB内存滑盖设计 黑莓9800报价2999元]]></title>
<pubDate>2014-11-04 13:50:19</pubDate>
</item>
<item>
<title><![CDATA[千元首选安卓智能机 联想A60特价仅售928元]]></title>
<pubDate>2014-11-25 12:50:46</pubDate>
</item>
<item>
<title><![CDATA[纤薄机身时尚大气 酷派安卓机D530售价1119元]]></title>
<pubDate>2014-11-25 12:50:46</pubDate>
</item>
</channel>