java - 递归 XML 解析器

标签 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>

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

我想以一个包含顶级函数的 ArrayList 结束,这些函数然后将它们的子函数递归地存储在对象中。

我需要它来处理无限深度的递归。

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

编辑:我在 Java 工作。

谢谢:)

最佳答案

除非你的文件很大,否则你可以使用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);
            }
        }
    }

}

结果:

[FUNCTION, NAME, CALLS, FUNCTION, NAME, CALLS, FUNCTION, NAME, FUNCTION, NAME]

关于java - 递归 XML 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13295621/

相关文章:

java - AES 如何使用不同的 IV 进行解密?

xml - 如何在xsd文件中的xpath中使用谓词?

javascript - 嵌套数组上的递归过滤器

java - 递归开关返回字符串

java - 为什么这个函数总是返回 0 或 1

java - 在另一个枚举的定义中迭代地使用一个枚举

Java检查文本文件中的每一行字符串并搜索该字符串是否存在

java - 使用运算符优先级从 JTextField 计算多个值

xml - Netbeans XML 工具更新中心

.net - 从现有的 XDocument 创建新的 XDocument