递归XML解析器

zin*_*ngo 2 java xml recursion xml-parsing

我有以下xml文件:

<?xml version="1.0"?>
<CONFIG>
    <FUNCTION>
        <NAME>FUNCT0</NAME>
        <CALLS>
            <FUNCTION>
            <NAME>FUNCT0_0</NAME>
            </FUNCTION>
        </CALLS>
        <CALLS>
            <FUNCTION>
            <NAME>FUNCT0_1</NAME>
            </FUNCTION>
        </CALLS>
    </FUNCTION>
    <FUNCTION>
        <NAME>FUNCT1</NAME>
    </FUNCTION>
</CONFIG>
Run Code Online (Sandbox Code Playgroud)

我有一个名为FunctionInfo的类,它存储一个函数的名称,还包含一个ArrayList,用于包含函数调用的子函数.

我想最终得到一个ArrayList,它包含顶层函数,然后递归地将它们的子函数存储在对象中.

我需要这个工作以无限期递归.

我的问题是编写可以执行此任务的递归XML解析器的最简单方法是什么?

编辑:我在Java工作.

谢谢 :)

the*_*dor 7

除非您的文件很大,否则您可以使用java DOM解析器(DOM解析器将文件保存在内存中)

给定一个节点(从根开始),您可以枚举其子节点,然后递归地在每个子节点上调用相同的函数.

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RecursiveDOM {
    public static void main(final String[] args) throws SAXException, IOException, ParserConfigurationException {
        new RecursiveDOM("file.xml");
    }

    public RecursiveDOM(final String file) throws SAXException, IOException, ParserConfigurationException {
        final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        final Document doc = docBuilder.parse(this.getClass().getResourceAsStream(file));
        final List<String> l = new ArrayList<String>();
        parse(doc, l, doc.getDocumentElement());
        System.out.println(l);
    }

    private void parse(final Document doc, final List<String> list, final Element e) {
        final NodeList children = e.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            final Node n = children.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                list.add(n.getNodeName());
                parse(doc, list, (Element) n);
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

结果:

[FUNCTION, NAME, CALLS, FUNCTION, NAME, CALLS, FUNCTION, NAME, FUNCTION, NAME]
Run Code Online (Sandbox Code Playgroud)