簡體   English   中英

Java:合並兩個XML NodeList

[英]Java: Concatinate two XML NodeList

我想串聯兩個節點列表並獲得一個新的節點列表。 目前,我的XML文檔如下所示:第一個XML:

<machine>
<values>
<value1> <...> </value1>
<value2> <...> </value2>
</values>

<days>
<value1> <...> </value1>
<value2> <...> </value2>
</days>
</machine>

第二個XML:

<machine>
<values>
<value3> <...> </value1>
<value4> <...> </value2>
</values>

<days>
<value3> <...> </value1>
<value4> <...> </value2>
</days>
</machine>

目前,我僅使用一種XML,並具有以下內容:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = null;
document = builder.parse(myxml.xml);
NodeList values = document.getElementsByTagName("values");
NodeList days = document.getElementsByTagName("days");

然后使用值和天處理NodeList。 我的程序運行正常。 現在,我以相同的方式創建第二個列表,因此:

DocumentBuilderFactory factory2 = DocumentBuilderFactory.newInstance();
DocumentBuilder builder2 = factory2.newDocumentBuilder();
Document document2 = null;
document2 = builder2.parse(myxml_second.xml);
NodeList values2 = document.getElementsByTagName("values");
NodeList days2 = document.getElementsByTagName("days");

這就提出了一個問題: 如何連接兩個列表,以便有一個列表values和一個列表days

我需要一個新的NodeList(類型),因為我的整個程序都可以使用NodeList類型。

我找到了解決該問題的多個線程,但是沒有任何效果或返回其他類型,但沒有返回NodeList。 一種方法有效:

public static NodeList join(final NodeList... lists) {

    class JoinedNodeList implements NodeList {
      public int getLength() {
        int len = 0;
        for (NodeList list : lists) {
          len += list.getLength();
        }
        return len;
      }

      public Node item(int index) {
        for (NodeList list : lists) {
          if (list.getLength() > index) {
            return list.item(index);
          } else {
            index -= list.getLength();
          }
        }
        return null;
      }
    }

    return new JoinedNodeList();
  }

然后,我的程序可以完美地與串聯的NodeList一起工作,但是它變慢了! 我認為這是由於覆蓋了這兩種方法,導致我在while或for循環中經常使用它們。 沒有串聯,只有一個大列表,程序運行很快。

我想提出以下優化措施,以解決您的“病慢”問題。

  • 在構建過程中,只需計算一次長度,因為這不會改變。
  • 在構造過程中將NodeList實例展平為原始數組,因此item()不必做太多工作。

假設

  • 列表不需要是動態的,即DOM更改未反映在列表中,這很可能是因為我認為getElementsByTagName()返回的結果始終不是動態的
  • 文檔相對較小,因此多余的內存不會成為問題。
  • 以后有很多讀物,這意味着在施工期間進行額外的工作可以獲得投資回報。

public static NodeList join(final NodeList... lists) {

    int count = 0;
    for (NodeList list : lists) {
        count += list.getLength();
    }
    final int length = count;

    Node[] joined = new Node[length];
    int outputIndex = 0;
    for (NodeList list : lists) {
        for (int i = 0, n = list.getLength(); i < n; i++) {
            joined[outputIndex++] = list.item(i);
        }
    }
    class JoinedNodeList implements NodeList {
        public int getLength() {
            return length;
        }

        public Node item(int index) {
            return joined[index];
        }
    }

    return new JoinedNodeList();
}

暫無
暫無

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

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