java 读取XML文件作为配置文件

首先,贴上自己的实例:

XML文件:NewFile.xml(该文件与src目录同级)



    
        s3Bucket
        
        get s3Bucket to get data
    
    
        s3key
        2016-12-19/12:26:36
        
    
    
        DynamoDBTable
        longyauntest
        
    
    
        KINESIS_STREAM_NAME
        
        
    
    
        Region
        cn-north-1
        
    
    
        LogFilePath
        
        save logfile to somewhere in s3
            eg:s3bucket://prefix key.
    

读取类:

String CONFIGXML_FILEPATH="NewFile.xml";
Map propertyMap = new HashMap();
try
{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(CONFIGXML_FILEPATH); // 获取根元素 Element configuration = doc.getDocumentElement(); // System.out.println(rootElement); // 获取根元素下面的子节点列表 NodeList propertyList = configuration.getChildNodes(); for (int i = 0; i < propertyList.getLength(); i++) { // 获取每个子节点 Node property = propertyList.item(i); String propertyName = null; String propertyValue = null; //该list包括单个property中的各个子节点,包括name、value、description NodeList nodeList = property.getChildNodes(); // 遍历该节点的详细信息 for (int j = 0; j < nodeList.getLength(); j++) { Node propertyDetail = nodeList.item(j); if (!propertyDetail.getNodeName().equals("#text")) { // 获取属性名 if (propertyDetail.getNodeName().equals("name")) { propertyName = propertyDetail.getTextContent(); } // 获取属性值 if (propertyDetail.getNodeName().equals("value")) { propertyValue = propertyDetail.getTextContent(); } } } // 如果属性值不为null,则将属性放入map中 if (propertyValue != null) { PropertyMap.put(propertyName, propertyValue); System.out.println(propertyName + ":" + propertyValue); } }
         //打印
// for(String key:property.keySet()) // { // System.out.println(key+":"+property.get(key)); // } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

 

 

ok,以下是别人的:

 

1.java读取xml文件的四种方法

2.四种生成和解析XML文档的方法详解(介绍+优缺点比较+示例)(这个妹纸比较6)

3.java解析xml文件(三种方式-(dom ,jdom ,dom4j)

 

转载于:https://www.cnblogs.com/not-NULL/p/5143275.html

你可能感兴趣的:(java 读取XML文件作为配置文件)