public static void main(String[] args){
try{
/**DocumentBuilderFactory
a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents
*/
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
/**DocumentBuilder
the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML
*/
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("link.xml");
/** Document.normalize();
对Document对象调用normalize(),
可以去掉XML文档中作为格式化内容的空白而映射在DOM树中的不必要的Text Node对象
*/
doc.normalize();
/** Document.getElementsByTagName(String)
Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree
*/
NodeList links=doc.getElementsByTagName("link");
for (int i=0;i<links.getLength();i++){
Element link=(Element) links.item(i);
System.out.print("Content: ");
System.out.println(link.getElementsByTagName("text").item(0).getFirstChild().getNodeValue());
System.out.print("URL: ");
System.out.println(link.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());
System.out.print("Author: ");
System.out.println(link.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
System.out.print("Date: ");
Element linkdate=(Element) link.getElementsByTagName("date").item(0);
String day=linkdate.getElementsByTagName("day").item(0).getFirstChild().getNodeValue();
String month=linkdate.getElementsByTagName("month").item(0).getFirstChild().getNodeValue();
String year=linkdate.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();
System.out.println(day+"-"+month+"-"+year);
System.out.print("Description: ");
System.out.println(link.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());
System.out.println();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}//*end main