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

10.30.2007
| 4356 views |
  • submit to reddit
        // description of your code here
given an xml:
<request>
	<action>managePermissions</action>
	<xml>
		<permission type='chm:allow-roles'>
			<role>role1</role>
			<role>role2</role>
			<role>role3</role>
		</permission>
		<permission type='chm:deny-roles'>
			<role>roleA</role>
			<role>roleB</role>
		</permission>
	</xml>
	<parameters>
		<uuid>xyz</uuid>
	</parameters>
</request>

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 {
        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<String> tempList = new ArrayList<String>();
          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;
  }