Java tutorial
//package com.java2s; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.traversal.DocumentTraversal; import org.w3c.dom.traversal.NodeFilter; import org.w3c.dom.traversal.NodeIterator; public class Main { private static Logger logger = Logger.getLogger(new Exception().getStackTrace()[0].getClassName()); public static void printNodesAndAttributes(String xmlStr) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { logger.info("Xml processing:"); DocumentBuilder db = dbf.newDocumentBuilder(); InputStream inStream = new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8)); // or InputSource inputSource = new InputSource( new StringReader( // xmlStr ) ); Document doc = db.parse(inStream); DocumentTraversal dt = (DocumentTraversal) doc; NodeIterator i = dt.createNodeIterator(doc, NodeFilter.SHOW_ELEMENT, null, false); Node node = i.nextNode(); while (node != null) { logger.info("Node type: " + node.getNodeType() + " Node name: " + node.getNodeName()); logger.info(" Attributes: " + attributesStr(node)); node = i.nextNode(); } } catch (Exception ex) { logger.error(ex); } } public static String attributesStr(Node node) { if (node == null) { return null; } StringBuffer attributes = new StringBuffer(); for (int i = 0; i < node.getAttributes().getLength(); i++) { attributes.append(node.getAttributes().item(i).getNodeName() + "=" + node.getAttributes().item(i).getNodeValue() + ", "); } if (attributes.length() > 1) { attributes.delete(attributes.length() - 2, attributes.length()); } else { attributes.append(node.getNodeName() + " has NO attributes."); } return attributes.toString(); } }