xml parsing using content handler
given an xml:
1 2 <request> 3 <action>managePermissions</action> 4 <xml> 5 <permission type='chm:allow-roles'> 6 <role>role1</role> 7 <role>role2</role> 8 <role>role3</role> 9 </permission> 10 <permission type='chm:deny-roles'> 11 <role>roleA</role> 12 <role>roleB</role> 13 </permission> 14 </xml> 15 <parameters> 16 <uuid>xyz</uuid> 17 </parameters> 18 </request>
will parse into permission map
1 2 static Map<String, List<String>> getPermissionMap(String xml){ 3 final Map<String, List<String>> permissionMap = new HashMap<String, List<String>>(); 4 5 //handler will produce a permission map based on xml 6 ContentHandler allowDenyXmlHandler = new DefaultHandler() { 7 private String permissionType; 8 private List<String> roleList = new ArrayList<String>(); 9 private Stack<String> nodes = new Stack<String>(); 10 private StringBuilder roleBuffer = new StringBuilder(); 11 12 /** 13 * Get type of permission that is defined in type attribute 14 */ 15 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 16 nodes.push(qName.trim()); 17 //get type of permission 18 if(nodes.peek().equals(PERMISSION)){ 19 permissionType = attributes.getValue(PERMISSION_TYPE); 20 } 21 } 22 23 /** 24 * Get role data for specified role 25 */ 26 public void characters(char ch[], int start, int length) throws SAXException { 27 if(nodes.peek().equals(ROLE)){ 28 roleBuffer.append(ch, start, length); 29 } 30 } 31 32 /** 33 * Populate role list if role end tag, or populate permission map if permission end tag 34 */ 35 public void endElement(String uri, String localName, String qName) throws SAXException { 36 String nodeName = nodes.pop(); 37 if(nodeName.equals(ROLE)){ 38 roleList.add(roleBuffer.toString()); 39 roleBuffer.setLength(0); 40 }else if(nodeName.equals(PERMISSION)){ 41 List<String> tempList = new ArrayList<String>(); 42 tempList.addAll(roleList); 43 permissionMap.put(permissionType, tempList); 44 roleList.clear(); 45 } 46 } 47 48 public void endDocument() throws SAXException { 49 // sanity check 50 if (nodes.size() > 0) logger.error("Node stack is not empty !!!"); 51 } 52 }; 53 54 try { 55 SAXParser parser = null; 56 // get SAXParser 57 synchronized (XMLParserHelper.saxParserFactory) { 58 parser = XMLParserHelper.saxParserFactory.newSAXParser(); 59 } 60 // Set custom content handler 61 parser.getXMLReader().setContentHandler(allowDenyXmlHandler); 62 // parse xml 63 parser.getXMLReader().parse(new InputSource(new StringReader(xml))); 64 65 } catch (Exception e) { 66 logger.error("[DLA00002] Unable to process permissions from XML {" + xml + "}", e); 67 } 68 69 return permissionMap; 70 }