package com.lch.test;
import
import
import
import
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLParse {
public XMLParse(){
DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dombulider = domfac.newDocumentBuilder();
InputStream is = new FileInputStream("D:\\workspace6\\test\\src\\com\\lch\\test\\test.xml");
Document doc = dombulider.parse(is);
Element root = doc.getDocumentElement();
NodeList books = root.getChildNodes();
if(books != null){
for(int i=0; i<books.getLength(); i++){
Node book = books.item(i);
if(book.getNodeType() == Node.ELEMENT_NODE){
for(Node node=book.getFirstChild(); node!=null; node=node.getNextSibling()){
if(node.getNodeType() == Node.ELEMENT_NODE){
if(node.getNodeName().equals("name")){
String name1=node.getFirstChild().getNodeValue();
System.out.println(name1);
}else if(node.getNodeName().equals("price")){
String price=node.getFirstChild().getNodeValue();
System.out.println(price);
}
}
}
}
}
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new XMLParse();
}
}
====================================================================================
<?xml version="1.0" encoding="gb2312"?>
<books>
<book>
<name>我的书0</name>
<price>45¥</price>
</book>
<book>
<name>我的书1</name>
<price>45¥</price>
</book>
</books>
=======================================
输出结果
我的书0
45¥
我的书1
45¥
=======================================
我功力浅,你的XML文件在我看来定义有一些问题。
不嫌弃的话,你可以看看我帮你写的一个处理方法!