1.读取文件
<?xml version="1.0" encoding="UTF-8"?>
<books >
<book id ="001" >
<title > Harry Potter</title >
<author > J K. Rowling</author >
<price > $50.2</price >
</book >
<book id ="002" >
<title > Learning XML</title >
<author > Erik T. Ray</author >
<price > $90</price >
</book >
</books >
2.读取代码
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class xmlReader {
public static void main (String args[]) {
Element element = null ;
File f = new File("src/book.xml" );
DocumentBuilder db = null ;
DocumentBuilderFactory dbf = null ;
try {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
Document dt = db.parse(f);
element = dt.getDocumentElement();
System.out.println("root elements:" + element.getNodeName());
NodeList childNodes = element.getChildNodes();
for (int i = 0 ; i < childNodes.getLength(); i++) {
Node childnode = childNodes.item(i);
if ("book" .equals(childnode.getNodeName())) {
System.out.println("\r\n读取书本,id= "
+ childnode.getAttributes().getNamedItem("id" )
.getNodeValue() + ". " );
NodeList nodeDetail = childnode.getChildNodes();
for (int j = 0 ; j < nodeDetail.getLength(); j++) {
Node detail = nodeDetail.item(j);
if ("title" .equals(detail.getNodeName()))
System.out
.println("title: " + detail.getTextContent());
else if ("author" .equals(detail.getNodeName()))
System.out
.println("author: " + detail.getTextContent());
else if ("price" .equals(detail.getNodeName()))
System.out
.println("price: " + detail.getTextContent());
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}