gpt4 book ai didi

java - 递归 XML 解析器

转载 作者:数据小太阳 更新时间:2023-10-29 02:50:06 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com