Over a million developers have joined DZone.

Xml Parsing Using Content Handler

·
// description of your code here
given an xml:


	managePermissions
	
		
			role1
			role2
			role3
		
		
			roleA
			roleB
		
	
	
		xyz
	



will parse into permission map


static Map> getPermissionMap(String xml){
    final Map> permissionMap = new HashMap>();
    
    //handler will produce a permission map based on xml
    ContentHandler allowDenyXmlHandler = new DefaultHandler() {
      private String permissionType;
      private List roleList = new ArrayList();
      private Stack nodes = new Stack();
      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 {
        nodes.push(qName.trim());
        //get type of permission
        if(nodes.peek().equals(PERMISSION)){
          permissionType = attributes.getValue(PERMISSION_TYPE);
        }
      }

      /**
       * Get role data for specified role
       */
      public void characters(char ch[], int start, int length) throws SAXException {
        if(nodes.peek().equals(ROLE)){
          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();
        if(nodeName.equals(ROLE)){
          roleList.add(roleBuffer.toString());
          roleBuffer.setLength(0);  
        }else if(nodeName.equals(PERMISSION)){
          List tempList = new ArrayList();
          tempList.addAll(roleList);
          permissionMap.put(permissionType, tempList);
          roleList.clear();
        }
      }

      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
      parser.getXMLReader().setContentHandler(allowDenyXmlHandler);
      // 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;
  }
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}