项目学习主题七:读取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;
	      
   }
 }

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念