项目学习主题七:读取xml

前端之家收集整理的这篇文章主要介绍了项目学习主题七:读取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.f2er.com/xml/298601.html

猜你在找的XML相关文章