使用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 + "    ");
            }
        }
    }
}


相关文章:

  • 2021-09-14
  • 2021-09-04
  • 2022-12-23
猜你喜欢
  • 2021-07-30
  • 2021-11-09
  • 2022-01-09
  • 2021-12-26
  • 2021-10-19
  • 2021-05-27
相关资源
相似解决方案