java读取xml文件

 1 import java.io.File;  
 2 import javax.xml.parsers.DocumentBuilder;  
 3 import javax.xml.parsers.DocumentBuilderFactory;  
 4 import javax.xml.parsers.ParserConfigurationException;
 5 import org.w3c.dom.Attr;  
 6 import org.w3c.dom.Comment;  
 7 import org.w3c.dom.Document;  
 8 import org.w3c.dom.Element;  
 9 import org.w3c.dom.NamedNodeMap;  
10 import org.w3c.dom.Node;  
11 import org.w3c.dom.NodeList;  
12 
13 
14 public class ReadXML {
15     /**
16      * 
17      * @param name ---userCheck/MakerGet/MakerName/StorCD
18      * @return
19      */
20     public static String getXML(String name){
21         String classPath = ReadXML.class.getResource("/").getPath();
22         
23         // step 1: 获得dom解析器工厂(工厂的作用是用于创建具体的解析器)  
24         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
25           
26         // step 2:获得具体的dom解析器  
27         DocumentBuilder db;
28         String result="";
29         try {
30             db = dbf.newDocumentBuilder();
31             Document document = db.parse(new File(classPath+"CGI.xml"));  
32             // step3: 解析一个xml文档,获得Document对象(根结点)  
33             NodeList list = document.getElementsByTagName("CGISettings");
34             System.out.println(list.getLength());
35             Element element = (Element)list.item(0);  
36             result = element.getElementsByTagName(name).item(0).getFirstChild().getNodeValue();  
37                      
38         } catch (Exception e) {
39             // TODO Auto-generated catch block
40             e.printStackTrace();
41         }  
42           
43         return result;
44     }
45     public static void main(String[] args) {
46         System.out.println(getXML("userCheck"));
47     }
48 }
View Code
原文地址:https://www.cnblogs.com/blackheartinsunshine/p/6409039.html