Tuesday, May 04, 2010

StudyNote--III DML--JAVA DOM XML

import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.lang.*;
import javax.xml.xpath.*;

public class DOMSearch{
public static void main(String[] arg) throws NullPointerException{
String SeriesName=null;
  if (arg.length >= 1) {
     SeriesName = arg[0];
//In Java whether input has double quotation marks or not,the outputs are the same
}else if(arg.length==0){
         System.out.println("No Series name input");
}
try{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
//Specifies that the parser produced by this code will provide support for XML namespaces,never forget this
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("TVGuide.xml");
doc.normalize();
/*可以去掉XML文档中作为格式化内容的空白而映射在DOM树中的不必要的Text Node对象。否则你得到的DOM树可能并不如你所想象的那样。特别是在输出的时候,这个normalize()更为有用*/
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
NodeList list1=doc.getElementsByTagName("Program");
  String Name="TVGuide/Channel/Program[Series='"+SeriesName+"']/../Name/text()";
/*To combine some string for the coming XPath Search,also we can use other ways to combine strings,like StringBuilder and StringBuffer
Examples: String Name=new StringBuffer().append("TVGuide/Channel/Program[Series='").append(SeriesName).append("']/../Name/text()").tostring();
This example use toString() to convert StringBuffer to String in case Name can be used in the next xpath.evalute which needs String value
String Name=new StringBuilder().append("TVGuide/Channel/Program[Series='").append(SeriesName).append("']/../Name/text()").tostring();
This is the same as the StringBuffer example
StringBuffer is thread-safe and better to be used in multi-threads while StringBuilder is not thread-safe and it has better to be used in single-thread as it is fast.
*/
      NodeList nodelist=(NodeList)xpath.evaluate(Name,doc,XPathConstants.NODESET);
      if(nodelist.getLength()==0){
      System.out.println("Series '"+SeriesName+"' Not Found");
      }else{
      for(int i=0;i<nodelist.getLength();i++){
      System.out.println(nodelist.item(i).getNodeValue());
      String StartTime="TVGuide/Channel[Name='"+nodelist.item(i).getNodeValue()+"']/Program[Series='"+SeriesName+"']/Start/text()";
      NodeList nodelist1=(NodeList)xpath.evaluate(StartTime,doc,XPathConstants.NODESET);
      for(int j=0;j<nodelist1.getLength();j++){
  System.out.println(nodelist1.item(j).getNodeValue());
       }
      }
     }
}catch(Exception e){
e.printStackTrace();
}
}
}

Labels: , ,