Java递归读取XML文件,无需使用for循环。

huangapple go评论69阅读模式
英文:

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 currentNode = nodeList.item(i);
        if (currentNode.getNodeValue() != null && !currentNode.getNodeValue().contains("\n")) {
            System.out.println(" Value: " + currentNode.getNodeValue());
        }
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) currentNode;
            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循环或额外方法的情况下获得相同的结果(只用一个方法实现完全递归)?

英文:

I'm currently trying to create a completely recursive method (without iteration like for loop) that reads an Xml file and returns the names and values of the nodes.

I've come this far:

 private static void getNodes(Node node){
         System.out.println(&quot;Node: &quot; + node.getNodeName());
         NodeList nodeList = node.getChildNodes();
         for (int i = 0; i &lt; nodeList.getLength(); i++) {
             Node currentode = nodeList.item(i);
             if (currentode.getNodeValue() != null &amp;&amp; currentode.getNodeValue().contains(&quot;\n&quot;) == false){
                 System.out.println(&quot; Value: &quot; +  currentode.getNodeValue());
             }
             if (currentode.getNodeType() == Node.ELEMENT_NODE) {
                 Element element = (Element) currentode;
                 getNodes(element);
             }
         }
     }

The call:

File xmlFile = new File(&quot;src/users.xml&quot;);

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);

doc.getDocumentElement().normalize();

getNodes( doc.getDocumentElement());

The Xml file:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;users&gt;
    &lt;user id=&quot;1&quot;&gt;
        &lt;firstname&gt;Peter&lt;/firstname&gt;
        &lt;lastname&gt;Brown&lt;/lastname&gt;
        &lt;occupation&gt;programmer&lt;/occupation&gt;
    &lt;/user&gt;
    &lt;user id=&quot;3&quot;&gt;
        &lt;firstname&gt;Lucy&lt;/firstname&gt;
        &lt;lastname&gt;Gordon&lt;/lastname&gt;
        &lt;occupation&gt;teacher&lt;/occupation&gt;
    &lt;/user&gt;
&lt;/users&gt;

The output:

Node: users
Node: user
Node: firstname
 Value: Peter
Node: lastname
 Value: Brown
Node: occupation
 Value: programmer
Node: user
…

How can I get the same result without using a for loop or additional method (complete recurisve with one method)?

答案1

得分: 0

假设这是为学校项目或学习而做的。

通常,我们通过将集合递归地视为链表来处理其中的元素,其中有一个 头部(集合中的第一个元素)和一个 尾部(集合的其余部分)。

以使用字符串数组的基本示例为例:

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);
}
英文:

Assuming this is for a school project or for learning.

Typically we deal with a collection of things recursively by treating the collection as if it were a linked list, with a head (the first item in the collection) and a tail (the rest of the collection).

A basic example using arrays of strings:

private static void printStrings(String[] strings) {
    if (strings.length &gt; 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 = {&quot;One&quot;,&quot;Two&quot;,&quot;Three&quot;};
    printStrings(strings);
}

答案2

得分: 0

public static void getNodes(Node node) {
    if (node != null) {
        System.out.println("节点: " + 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(" 值: " + node.getNodeValue());

    if (node.getNodeType() == Node.ELEMENT_NODE)
        getNodes(node);

    getNodes(nodes, i + 1);
}
英文:
public static void getNodes(Node node) {
    if (node != null) {
        System.out.println(&quot;Node: &quot; + 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 &amp;&amp; !node.getNodeValue().contains(&quot;\n&quot;))
        System.out.println(&quot; Value: &quot; + node.getNodeValue());

    if (node.getNodeType() == Node.ELEMENT_NODE)
        getNodes(node);

    getNodes(nodes, i + 1);
}

huangapple
  • 本文由 发表于 2020年10月18日 05:09:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64407374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定