首页 > 代码库 > java XML解析

java XML解析

package com.kpsh.myself;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.w3c.dom.NodeList;

import com.opensymphony.xwork2.ActionSupport;

public class DoAction extends ActionSupport{

 public static void queryXml(){
  try{
            //得到DOM解析器的工厂实例
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //从DOM工厂中获得DOM解析器
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //把要解析的xml文档读入DOM解析器
            //org.w3c.dom.Document doc = dbBuilder.parse("src/school.xml");
            //System.out.println("处理该文档的DomImplementation对象  = "+ doc.getImplementation());
            //得到文档名称为Student的元素的节点列表
            //NodeList nList = doc.getElementsByTagName("Student");
            //遍历该集合,显示结合中的元素及其子元素的名字
      /*      for(int i = 0; i< nList.getLength() ; i ++){
                Element node = (Element)nList.item(i);
                System.out.println("Name: "+ node.getElementsByTagName("Name").item(0).getFirstChild().getNodeValue());
                System.out.println("Num: "+ node.getElementsByTagName("Num").item(0).getFirstChild().getNodeValue());
                System.out.println("Address: "+ node.getElementsByTagName("Address").item(0).getFirstChild().getNodeValue());
                System.out.println("Tel: "+ node.getElementsByTagName("Tel").item(0).getFirstChild().getNodeValue());
            }*/

   File file = new File("src/test.xml");
   FileInputStream fs = new FileInputStream(file);
   byte[] data = http://www.mamicode.com/new byte[(int) >   fs.read(data);
   fs.close();
   Document dom = DocumentHelper.parseText(new String(data, "UTF-8"));

   if(dom != null){
    Element root = dom.getRootElement();
    
/*    if ("ip-filter".equals(root.getName())) {
     Element web_ip = root.element("web_ip");
     if (web_ip != null) {      
      System.out.println(web_ip.getTextTrim());
     }
     Element cooee_ip = root.element("cooee_ip");
     if (cooee_ip != null) {
      List<Element> ips = cooee_ip.elements();
      for (Element e : ips) {
       System.out.println(e.getTextTrim());
      }
     }
       }*/
    
    if ("Test".equals(root.getName())) {
     Element stu = root.element("Student");
     if (stu != null) {
      List<Element> ips = stu.elements();
      for (Element e : ips) {
       System.out.println(e.getTextTrim());
      }
     }
       }
    
     }  
           
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
 
 public String execute() throws Exception {
  //读取
  DoAction.queryXml();
  ParseXML.createXMLFile();
  
  return SUCCESS;
 }
}