项目学习主题七:读取xml

来源:互联网 发布:恐怖悬疑电影 知乎 编辑:程序博客网 时间:2024/06/12 00:49

读取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 localName, 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;         } }


0 0
原创粉丝点击