[英]Java read xml file recursive without for loop
我目前正在嘗試創建一個完全遞歸的方法(沒有像 for 循環那樣的迭代),它讀取一個 Xml 文件並返回節點的名稱和值。
我已經走到這一步了:
private static void getNodes(Node node){
System.out.println("Node: " + node.getNodeName());
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentode = nodeList.item(i);
if (currentode.getNodeValue() != null && currentode.getNodeValue().contains("\n") == false){
System.out.println(" Value: " + currentode.getNodeValue());
}
if (currentode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) currentode;
getNodes(element);
}
}
}
電話:
File xmlFile = new File("src/users.xml");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
doc.getDocumentElement().normalize();
getNodes( doc.getDocumentElement());
Xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="1">
<firstname>Peter</firstname>
<lastname>Brown</lastname>
<occupation>programmer</occupation>
</user>
<user id="3">
<firstname>Lucy</firstname>
<lastname>Gordon</lastname>
<occupation>teacher</occupation>
</user>
</users>
輸出:
Node: users
Node: user
Node: firstname
Value: Peter
Node: lastname
Value: Brown
Node: occupation
Value: programmer
Node: user
…
如何在不使用 for 循環或其他方法(使用一種方法完全遞歸)的情況下獲得相同的結果?
假設這是用於學校項目或學習。
通常,我們通過將集合視為一個鏈表來遞歸處理事物的集合,它有一個頭(集合中的第一個項目)和一個尾(集合的其余部分)。
使用字符串數組的基本示例:
private static void printStrings(String[] strings) {
if (strings.length > 0) {
String head = strings[0];
System.out.println(head);
String[] tail = Arrays.copyOfRange(strings, 1, strings.length);
printStrings(tail);
}
}
public static void main(String[] args) {
String[] strings = {"One","Two","Three"};
printStrings(strings);
}
public static void getNodes(Node node) {
if (node != null) {
System.out.println("Node: " + node.getNodeName());
getNodes(node.getChildNodes(), 0);
}
}
private static void getNodes(NodeList nodes, int i) {
Node node = nodes.item(i);
if (node == null)
return;
if (node.getNodeValue() != null && !node.getNodeValue().contains("\n"))
System.out.println(" Value: " + node.getNodeValue());
if (node.getNodeType() == Node.ELEMENT_NODE)
getNodes(node);
getNodes(nodes, i + 1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.