java

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.NodeList;
import org.w3c.dom.Text;


public class XMLRead {
  public static void main(String[] args) {
   try {  
    //建立DocumentBuilderFactory对象
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
    // 建立DocumentBuilder对象
    DocumentBuilder builder = factory.newDocumentBuilder();  
  // 用DocumentBuilder对象的parse方法引入文件建立Document对象
    Document document = builder.parse(new File("d:\\web.xml"));  
//    Element rootElement = document.getDocumentElement();
    //用document的getElementsByTagName方法获取xml标签名
    NodeList list = (NodeList) document.getElementsByTagName("context-param"); 
    for(int i=0;i<list.getLength();i++){
   // 得到一个节点,需要强制转换为Element,这里list是Element的父类
     Element element = (Element) list.item(i);  
     NodeList lists = element.getElementsByTagName("param-name");
   // 此元素有子节点,获取所有子节点,返回一个t
     Text t = (Text)lists.item(0).getFirstChild();
     System.out.println(t.getNodeValue());
    }
    } catch (Exception e) {  
     System.out.println("exception:" + e.getMessage()); 
     }
    }
}

你可能感兴趣的:(java)