[英]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循環中經常使用它們。 沒有串聯,只有一個大列表,程序運行很快。
我想提出以下優化措施,以解決您的“病慢”問題。
假設
碼
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.