微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

项目学习主题七:读取xml

读取xml:

 public class readxml { 


   class XMLHandler extends DefaultHandler { 
      public Map<String,String> resultMap;
      private boolean title = false; 
      public String searchItem;
    
      // Called at start of an XML document 
      @Override 
      public void startDocument() throws SAXException { 
         resultMap=new HashMap<String,String>();
      } 
      // Called at end of an XML document 
      @Override 
      public void endDocument() throws SAXException {  
    	  
      } 
      
      @Override 
      public void startElement(String uri,String localName,String qName,Attributes atts) throws SAXException { 
         // Using qualified name because we are not using XMLs prefixes here. 
         if (!qName.equals("")) { 
        	searchItem=qName;
            title = true; 
         } 
      } 
   
      @Override 
      public void endElement(String namespaceURI,String qName) 
         throws SAXException { 
         // End of processing current element 
         if (title) { 
            title = false; 
         } 
      } 
   			
      @Override 
      public void characters(char[] ch,int start,int length) { 
         // Processing character data inside an element 
         if (title) { 
            String searchResult = new String(ch,start,length);
            if(!searchResult.equals(""))
            	resultMap.put(searchItem,searchResult);
         } 
      } 		
   } 
   /**
    * This function is used to get informations from a certain XML.
   
    */
   public static Map<String,String> getXmlInfo(String xmlName)
   		throws SAXException,IOException { 
	      XMLReader parser = XMLReaderFactory.createXMLReader(); 
	      XMLHandler xmlHandler = (new readxml()).new XMLHandler(); 
	      parser.setContentHandler(xmlHandler); 
	      parser.parse("./conf/"+xmlName);
	      return xmlHandler.resultMap;
	      
   }
 }

原文地址:https://www.jb51.cc/xml/298601.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。