簡體   English   中英

如何通過Java中的int數組編號創建多個XML元素

[英]How to create multiple XML elements by the numbers of an int Array in Java

我一直在處理一種算法,用Java創建xml文件的自動結構。

這個想法是對XML文件中的元素進行計數,然后將它們放入列表中,然后對其中的重復元素進行計數,最后創建另一個XML節點,其中包含該列表中重復數字的數量。

我通過使用Map <String, Long>Collections來獲取重復的元素和出現次數,從而解決了第一個問題。

我通過將出現次數轉換為int值,將它們放在Arraylist中。

Collection test = counterMap.values();
        List <Integer> list = new ArrayList(test);
        Iterator listIteration = list.iterator();
        ArrayList <Integer> intValues = new ArrayList <>();
        while (listIteration.hasNext()) {
            int Values = Integer.parseInt(listIteration.next().toString());
            intValues.add(Values);
        }

現在,我有一個int值的列表,例如intValues=[1,3,3,4,2,2]

通過使用該列表,我想使用此列表中的數字創建一個XML元素。 我為每個循環嘗試克服它。 但是我不能。

Element example;

        for (int i = 0; i <= list.size(); i++) {
            root = doc.createElement("root");
            pattern.appendChild(root);
            //for (Iterator<Integer> h = intValues.iterator(); h.hasNext();) {
            //Integer item = h.next();
            for (Integer a : intValues) {
                for (int b = 1; b < a; b++) {
                    example = doc.createElement("example");
                    root.appendChild(example);

                }

            }
        }

示例輸出可能是:

<root>
  <example>
<root>
<root>
  <example>
  <example>
  <example>
<root>
<root>
  <example>
  <example>
  <example>
<root>
<root>
  <example>
  <example>
  <example>
  <example>
<root>

(int arrayList中的元素數)

任何想法都將繼續前進,對於錯誤或不清楚的部分,我們深表歉意。

##########解決方案更新############

我找到了解決方案,在這里添加了它,這樣任何人都可以使用,如果他們最終遇到相同的問題。 感謝您的所有幫助。

for (Integer a : intValues) {

            root= doc.createElement("root");

            for (int b = 1; b <= a; b++) {

                pattern.appendChild(root);
                example= doc.createElement("example");
                rule.appendChild(example);

            }
        }

這部分for (int i = 0; i <= list.size(); i++)是不必要的。 只需將其刪除並在循環中更改位順序即可。 輸出正是我想要的。

##########解決方案更新############

我找到了解決方案,在這里添加了它,這樣任何人都可以使用,如果他們最終遇到相同的問題。 感謝您的所有幫助。

for (Integer a : intValues) {

            root= doc.createElement("root");

            for (int b = 1; b <= a; b++) {

                pattern.appendChild(root);
                example= doc.createElement("example");
                rule.appendChild(example);

            }
        }

這部分for (int i = 0; i <= list.size(); i++)是不必要的。 只需將其刪除並在循環中更改位順序即可。 輸出正是我想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM