DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Mark has posted 3 posts at DZone. View Full User Profile

Xml Parsing Using Content Handler

  • submit to reddit
        // description of your code here
given an xml:
		<permission type='chm:allow-roles'>
		<permission type='chm:deny-roles'>

will parse into permission map

static Map<String, List<String>> getPermissionMap(String xml){
    final Map<String, List<String>> permissionMap = new HashMap<String, List<String>>();
    //handler will produce a permission map based on xml
    ContentHandler allowDenyXmlHandler = new DefaultHandler() {
      private String permissionType;
      private List<String> roleList = new ArrayList<String>();
      private Stack<String> nodes = new Stack<String>();
      private StringBuilder roleBuffer = new StringBuilder();
       * Get type of permission that is defined in type attribute
      public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //get type of permission
          permissionType = attributes.getValue(PERMISSION_TYPE);

       * Get role data for specified role
      public void characters(char ch[], int start, int length) throws SAXException {
          roleBuffer.append(ch, start, length);  

       * Populate role list if role end tag, or populate permission map if permission end tag
      public void endElement(String uri, String localName, String qName) throws SAXException {
        String nodeName = nodes.pop();
        }else if(nodeName.equals(PERMISSION)){
          List<String> tempList = new ArrayList<String>();
          permissionMap.put(permissionType, tempList);

      public void endDocument() throws SAXException {
        // sanity check
        if (nodes.size() > 0) logger.error("Node stack is not empty !!!");
    try {
      SAXParser parser = null;
      // get SAXParser
      synchronized (XMLParserHelper.saxParserFactory) {
        parser = XMLParserHelper.saxParserFactory.newSAXParser();
      // Set custom content handler
      // parse xml
      parser.getXMLReader().parse(new InputSource(new StringReader(xml)));

    } catch (Exception e) {
      logger.error("[DLA00002] Unable to process permissions from XML {" + xml + "}", e);
    return permissionMap;