<?xml version="1.0" encoding="UTF-8"?>
<links>
<link>
<text> My Information1 </text>
<url> jinbogameboy@sina.com </url>
<author> jinbogameboy1 </author>
<date>
<day>23</day>
<month>7</month>
<year>2007</year>
</date>
<description>我是吴锦波</description>
</link>
<link>
<text> My Information2 </text>
<url> jinbogameboy@sina.com </url>
<author> jinbogameboy2 </author>
<date>
<day>23</day>
<month>7</month>
<year>2009</year>
</date>
<description>
我来自广东
</description>
</link>
</links>
测试程序
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class XmlParser {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null ;
Document doc = null ;
try {
builder = factory.newDocumentBuilder();
// doc = builder.parse("links.xml");//对于这种写法,文件要放在工程的根目录下
doc = builder.parse("src\\xml\\parser\\links.xml");
} catch (Exception e) {
e.printStackTrace();
}
doc.normalize();
NodeList links = doc.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); i++) {
System.out.println("第"+i+"次循环: ");
Element link = (Element)links.item(i);
System.out.println("Text: "+link.getElementsByTagName("text").item(0).getFirstChild().getNodeValue());;
System.out.println("URL: "+link.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());;
System.out.println("Author: "+link.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());;
Element datenode = (Element)link.getElementsByTagName("date").item(0);
String date = datenode.getElementsByTagName("day").item(0).getFirstChild().getNodeValue();
String month = datenode.getElementsByTagName("month").item(0).getFirstChild().getNodeValue();
String year = datenode.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();
System.out.println("Time: "+year+"年"+month+"月"+date+"日");
System.out.println("Descrition: "+link.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());
}
}
}