2013年11月6日 星期三

java-xml-read

inf : http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

import java.io.File;
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;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class xmlread {
static Date date = new Date();
static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//設定日期格式
static String dateString = sdf.format(date);
static String filename="spooled"+dateString+".xml";
static String Locate="10869";
static String r_P, r_F,r_M;

public static void main(String argv[]) {
r_P=""; r_F=""; r_M="";
Run ();} public static void Run() {

  try {
//  File file = new File("spooled20130226.xml");
  File file = new File(filename);
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
//  System.out.println("Root element " + doc.getDocumentElement().getNodeName());
  NodeList nodeLst = doc.getElementsByTagName("package");
//  System.out.println("Information of all employees");

  for (int s = 0; s < nodeLst.getLength(); s++) {

    Node fstNode = nodeLst.item(s);
   
    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

      Element fstElmnt = (Element) fstNode;
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("M");
      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
r_M=((Node) lstNm.item(0)).getNodeValue();
  //    System.out.print(" M : " +r_M);
      NodeList lstNmElmntLst_F  = fstElmnt.getElementsByTagName("F");
      Element lstNmElmnt_F = (Element) lstNmElmntLst_F.item(0);
      NodeList lstNm_F = lstNmElmnt_F.getChildNodes();
r_F=((Node) lstNm_F.item(0)).getNodeValue();
    //  System.out.print(" F : " +r_F );
      NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("P");
      Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
      NodeList fstNm = fstNmElmnt.getChildNodes();
r_P=((Node) fstNm.item(0)).getNodeValue();
//      System.out.println(" P : "  +r_P );
int _2;int _1;
try{_1=Integer.valueOf(Locate);} catch (
NumberFormatException e){_1=-2;}
try{_2=Integer.valueOf(r_P);} catch (
NumberFormatException e){_2=-1;}
if (_1==_2){
      //System.out.println(r_P);
break;}
else {r_F="";r_M="";}

    }

  }
  }
catch (Exception e) {}
//catch (Exception e) { e.printStackTrace();}
//catch (SAXParseException e){}

 }
}

沒有留言:

張貼留言