java读取XML

  1. package org.csc.xml;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9. import javax.xml.parsers.DocumentBuilder;
  10. import javax.xml.parsers.DocumentBuilderFactory;
  11. import javax.xml.parsers.ParserConfigurationException;
  12. import org.w3c.dom.Document;
  13. import org.w3c.dom.Element;
  14. import org.w3c.dom.NodeList;
  15. import org.xml.sax.SAXException;
  16. import pojos.DicProvinceCity;
  17. import pojos.DicProvinceCityDAO;
  18. public class ViewXml {
  19.     private Document doc;
  20.     /**
  21.      * 初始化
  22.      * @param xmlFile
  23.      * @throws ParserConfigurationException
  24.      * @throws IOException 
  25.      * @throws SAXException 
  26.      */
  27.     public void init(String xmlFile) throws ParserConfigurationException, SAXException, IOException{
  28.         DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
  29.         DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
  30.         doc = documentBuilder.parse(new File(xmlFile));
  31.     }
  32.     /**得到省市***/
  33.     public Map<String,Integer> getProvinceMap(String xmlFile) throws Exception{
  34.         init(xmlFile);
  35.         Map<String,Integer> map = new HashMap<String, Integer>();
  36.         /***根节点**/
  37.         Element rootElement = doc.getDocumentElement();
  38.         System.out.println("根节点:"+rootElement.getTagName());
  39.         /**得到元素名为classic1的节点**/
  40.         NodeList nodeList = rootElement.getElementsByTagName("class1");
  41.         for(int i=0;i<nodeList.getLength();i++){
  42.             Integer id = Integer.parseInt(nodeList.item(i).getAttributes().item(0).getNodeValue());
  43.             String name = nodeList.item(i).getAttributes().item(1).getNodeValue();
  44.             System.out.println(id+name);
  45.             map.put(name, id);
  46.         }
  47.         return map;
  48.     }
  49. }
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值