使用w3c dom采用递归实现xml文件的解析读取。
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class MAIN { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringComments(true); factory.setValidating(true); String nodeName = ""; Element element = null; Node node = null; int childNodesLength = 0; Document xmlDoc = builder.parse("C:\development\workspace\nm-server\resource\output\lp\problem_out.xml"); Element root = xmlDoc.getDocumentElement(); listNodes(root,""); } public static void listNodes(Node node, String space) { Element element = null; if (node.getNodeType() == Node.ELEMENT_NODE) { element = (Element)node; System.out.println(space + element.getTagName()); } NodeList list = node.getChildNodes(); int childNodesLength = list.getLength(); if (childNodesLength > 0) { for (int i = 0; i < childNodesLength; i++) { listNodes(list.item(i), space + " "); } } } }