fork(7) download
  1. import java.io.ByteArrayInputStream;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import org.w3c.dom.Document;
  9. import org.w3c.dom.Node;
  10. import org.w3c.dom.NodeList;
  11.  
  12. import javax.xml.parsers.DocumentBuilder;
  13. import javax.xml.parsers.DocumentBuilderFactory;
  14.  
  15. /**
  16.  *
  17.  * @author Pritom K Mondal
  18.  * @published 12th September 2013 08:04 PM
  19.  */
  20. class XmlParser {
  21. private String xmlString = "";
  22. private File xmlFile = null;
  23. private Document doc = null;
  24.  
  25. /**
  26.   * @param args the command line arguments
  27.   */
  28. public static void main(String[] args) {
  29. String xmlString = "YOUR XML STRING HERE IF YOU WANT PARSE DATA FROM STRING";
  30. XmlParser xmlParser = new XmlParser(xml);
  31.  
  32. Map xmlMap = xmlParser.parseXML();
  33. print(xmlMap, 0);
  34. }
  35.  
  36. public XmlParser(String xmlString) {
  37. this.xmlString = xmlString;
  38. }
  39.  
  40. public XmlParser(File xmlFile) {
  41. this.xmlFile = xmlFile;
  42. }
  43.  
  44. public Map parseXML() {
  45. try {
  46. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  47. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  48.  
  49. if (this.xmlFile != null) {
  50. doc = dBuilder.parse(this.xmlFile);
  51. }
  52. else {
  53. doc = dBuilder.parse( new ByteArrayInputStream(xmlString.getBytes()) );
  54. }
  55.  
  56. doc.getDocumentElement().normalize();
  57.  
  58. NodeList resultNode = doc.getChildNodes();
  59.  
  60. HashMap result = new HashMap();
  61. XmlParser.MyNodeList tempNodeList = new XmlParser.MyNodeList();
  62.  
  63. String emptyNodeName = null, emptyNodeValue = null;
  64.  
  65. for(int index = 0; index < resultNode.getLength(); index ++) {
  66. Node tempNode = resultNode.item(index);
  67. if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
  68. tempNodeList.addNode(tempNode);
  69. }
  70. emptyNodeName = tempNode.getNodeName();
  71. emptyNodeValue = tempNode.getNodeValue();
  72. }
  73.  
  74. if (tempNodeList.getLength() == 0 && emptyNodeName != null
  75. && emptyNodeValue != null) {
  76. result.put(emptyNodeName, emptyNodeValue);
  77. return result;
  78. }
  79.  
  80. this.parseXMLNode(tempNodeList, result);
  81. return result;
  82. } catch (Exception ex) {
  83. ex.printStackTrace();
  84. return null;
  85. }
  86. }
  87.  
  88. private void parseXMLNode(NodeList nList, HashMap result) {
  89. for (int temp = 0; temp < nList.getLength(); temp++) {
  90. Node nNode = nList.item(temp);
  91. if (nNode.getNodeType() == Node.ELEMENT_NODE
  92. && nNode.hasChildNodes()
  93. && nNode.getFirstChild() != null
  94. && (nNode.getFirstChild().getNextSibling() != null
  95. || nNode.getFirstChild().hasChildNodes())) {
  96. NodeList childNodes = nNode.getChildNodes();
  97. XmlParser.MyNodeList tempNodeList = new XmlParser.MyNodeList();
  98. for(int index = 0; index < childNodes.getLength(); index ++) {
  99. Node tempNode = childNodes.item(index);
  100. if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
  101. tempNodeList.addNode(tempNode);
  102. }
  103. }
  104. HashMap dataHashMap = new HashMap();
  105. if (result.containsKey(nNode.getNodeName()) && result.get(nNode.getNodeName()) instanceof List) {
  106. List mapExisting = (List) result.get(nNode.getNodeName());
  107. mapExisting.add(dataHashMap);
  108. } else if(result.containsKey(nNode.getNodeName())) {
  109. List counterList = new ArrayList();
  110. counterList.add(result.get(nNode.getNodeName()));
  111. counterList.add(dataHashMap);
  112. result.put(nNode.getNodeName(), counterList);
  113. } else {
  114. result.put(nNode.getNodeName(), dataHashMap);
  115. }
  116. if (nNode.getAttributes().getLength() > 0) {
  117. Map attributeMap = new HashMap();
  118. for(int attributeCounter = 0;
  119. attributeCounter < nNode.getAttributes().getLength();
  120. attributeCounter++) {
  121. attributeMap.put(
  122. nNode.getAttributes().item(attributeCounter).getNodeName(),
  123. nNode.getAttributes().item(attributeCounter).getNodeValue()
  124. );
  125. }
  126. dataHashMap.put("<<attributes>>", attributeMap);
  127. }
  128. this.parseXMLNode(tempNodeList, dataHashMap);
  129. } else if (nNode.getNodeType() == Node.ELEMENT_NODE
  130. && nNode.hasChildNodes() && nNode.getFirstChild() != null
  131. && nNode.getFirstChild().getNextSibling() == null) {
  132. this.putValue(result, nNode);
  133. } else if(nNode.getNodeType() == Node.ELEMENT_NODE) {
  134. this.putValue(result, nNode);
  135. }
  136. }
  137. }
  138.  
  139. private void putValue(HashMap result, Node nNode) {
  140. HashMap attributeMap = new HashMap();
  141. Object nodeValue = null;
  142. if(nNode.getFirstChild() != null) {
  143. nodeValue = nNode.getFirstChild().getNodeValue();
  144. if(nodeValue != null) {
  145. nodeValue = nodeValue.toString().trim();
  146. }
  147. }
  148. HashMap nodeMap = new HashMap();
  149. nodeMap.put("<<value>>", nodeValue);
  150. Object putNode = nodeValue;
  151. if (nNode.getAttributes().getLength() > 0) {
  152. for(int attributeCounter = 0;
  153. attributeCounter < nNode.getAttributes().getLength();
  154. attributeCounter++) {
  155. attributeMap.put(
  156. nNode.getAttributes().item(attributeCounter).getNodeName(),
  157. nNode.getAttributes().item(attributeCounter).getNodeValue()
  158. );
  159. }
  160. nodeMap.put("<<attributes>>", attributeMap);
  161. putNode = nodeMap;
  162. }
  163. if (result.containsKey(nNode.getNodeName()) && result.get(nNode.getNodeName()) instanceof List) {
  164. List mapExisting = (List) result.get(nNode.getNodeName());
  165. mapExisting.add(putNode);
  166. } else if(result.containsKey(nNode.getNodeName())) {
  167. List counterList = new ArrayList();
  168. counterList.add(result.get(nNode.getNodeName()));
  169. counterList.add(putNode);
  170. result.put(nNode.getNodeName(), counterList);
  171. } else {
  172. result.put(nNode.getNodeName(), putNode);
  173. }
  174. }
  175.  
  176. class MyNodeList implements NodeList {
  177. List<Node> nodes = new ArrayList<Node>();
  178. int length = 0;
  179. public MyNodeList() {}
  180.  
  181. public void addNode(Node node) {
  182. nodes.add(node);
  183. length++;
  184. }
  185.  
  186. @Override
  187. public Node item(int index) {
  188. try {
  189. return nodes.get(index);
  190. } catch (Exception ex) {
  191. ex.printStackTrace();
  192. }
  193. return null;
  194. }
  195.  
  196. @Override
  197. public int getLength() {
  198. return length;
  199. }
  200. }
  201.  
  202. private static void print(Map map, Integer tab) {
  203. Iterator it = map.entrySet().iterator();
  204. while (it.hasNext()) {
  205. Map.Entry pairs = (Map.Entry) it.next();
  206. String key = pairs.getKey().toString();
  207. Object value = pairs.getValue();
  208. if (value instanceof Map) {
  209. System.out.println(getTab(tab) + key + " ==> [");
  210. print((Map) value, tab + 1);
  211. System.out.println(getTab(tab) + "]");
  212. }
  213. else if (value instanceof List) {
  214. System.out.println(getTab(tab) + key + " ==> [");
  215. print((List) value, tab + 1);
  216. System.out.println(getTab(tab) + "]");
  217. }
  218. else {
  219. System.out.println(getTab(tab) + key + " ==> " + value);
  220. }
  221. }
  222. }
  223.  
  224. private static void print(List list, Integer tab) {
  225. for (Integer index = 0; index < list.size(); index++) {
  226. Object value = list.get(index);
  227. if (value instanceof Map) {
  228. System.out.println(getTab(tab) + index.toString() + ": {");
  229. print((Map) value, tab + 1);
  230. System.out.println(getTab(tab) + "}");
  231. }
  232. else if (value instanceof List) {
  233. print((List) value, tab + 1);
  234. }
  235. else {
  236. System.out.println(getTab(tab) + index.toString() + ": " + value);
  237. }
  238. }
  239. }
  240.  
  241. public static String getTab(Integer tab) {
  242. String string = "";
  243. for (Integer index = 0; index < tab; index++) {
  244. string += " ";
  245. }
  246. return string;
  247. }
  248.  
  249. public static final String xml = "<?xml version='1.0'?>"+
  250. "<lib:library xmlns:lib='http://e...content-available-to-author-only...t.com/ns/library'"+
  251. " xmlns:hr='http://e...content-available-to-author-only...t.com/ns/person'>"+
  252. "<Purchase>"+
  253. "<PurchaseId>AAAAA</PurchaseId> "+
  254. "<PurchaseType>ONLINE</PurchaseType>"+
  255. "</Purchase>"+
  256. "<Purchase>"+
  257. "<PurchaseId>BBBBB</PurchaseId>"+
  258. "<PurchaseType>OFFLINE</PurchaseType>"+
  259. "</Purchase>"+
  260. "<Purchase paid='True'>"+
  261. "<Purchase9>"+
  262. "<Purchase2 nc='true'>List 1</Purchase2>"+
  263. "<Purchase2>List 2</Purchase2>"+
  264. "<hr:author>List 3.0</hr:author>"+
  265. "</Purchase9>"+
  266. "</Purchase>"+
  267. "</lib:library>";
  268. }
Success #stdin #stdout 0.13s 380928KB
stdin
Standard input is empty
stdout
lib:library ==> [
    <<attributes>> ==> [
        xmlns:hr ==> http://e...content-available-to-author-only...t.com/ns/person
        xmlns:lib ==> http://e...content-available-to-author-only...t.com/ns/library
    ]
    Purchase ==> [
        0: {
            PurchaseId ==> AAAAA
            PurchaseType ==> ONLINE
        }
        1: {
            PurchaseId ==> BBBBB
            PurchaseType ==> OFFLINE
        }
        2: {
            <<attributes>> ==> [
                paid ==> True
            ]
            Purchase9 ==> [
                Purchase2 ==> [
                    0: {
                        <<attributes>> ==> [
                            nc ==> true
                        ]
                        <<value>> ==> List 1
                    }
                    1: List 2
                ]
                hr:author ==> List 3.0
            ]
        }
    ]
]