Java 将节点添加到节点列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9757987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding node to a nodelist
提问by lonesome
my aim is to add nodes not at once to a NodeList but to add them in a loop in each iteration. i looked up the classes and methods for NodeList , but didnt find anything useful for it. is there anyway for doing this or should i use other interfaces? going to do something like below but the NodeList interface doesnt have the "add" method.then how can i add items?
我的目标是不是立即将节点添加到 NodeList 中,而是在每次迭代中将它们添加到循环中。我查找了 NodeList 的类和方法,但没有找到任何有用的东西。无论如何要这样做还是我应该使用其他接口?要做类似下面的事情,但 NodeList 接口没有“添加”方法。那么我如何添加项目?
static NodeList tryToGetThePoint;
while(true)
{
.
.
.
if(!"script".equals(myNode.getParentNode().getNodeName()))
{
tryToGetThePoint.add=myNode;
}
采纳答案by Perry Monschau
The critical bit about this is:
关于这一点的关键是:
"The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented."
“NodeList 接口提供了有序节点集合的抽象,而不定义或限制该集合的实现方式。”
In short: it's up to you to implement everything.
简而言之:一切都由您来实施。
Are you sure you can't use Lists instead? I mean, it depends what this is for?
您确定不能使用 Lists 吗?我的意思是,这取决于这是为了什么?
But if you do want to implement your own, this is roughly how it should be.
但是,如果您确实想实现自己的,则大致应该是这样。
public class MyNodeList implements NodeList {
Node root = null;
int length = 0;
public MyNodeList() {}
public void addNode(Node node) {
if(root == null)
root = node;
else
root.addChild(node);
length++;
}
public Node item(int index) {
if(index < 1) return root;
Node node = root;
while(index > 0) {
node = node.getFirstChild();
if(node == null) return node;
index--;
}
return node;
}
public int getLength() {
return length;
}
}
回答by Adrian Mouat
You have to remember that the nodes in a NodeList
are live- if you change them you are modifying the underlying DOM tree. Therefore it doesn't really make sense to add things to a NodeList
- where do you expect them to live in the tree?
您必须记住 a 中的节点NodeList
是活动的- 如果您更改它们,您正在修改底层 DOM 树。因此,将东西添加到 a 中并没有真正意义NodeList
- 您希望它们生活在树中的什么位置?
If you just want a list of Node
s unconnected with the document, just use List<Node>
. Otherwise, you will need to figure out where to add the nodes to the DOM tree and use the normal methods.
如果您只想要Node
与文档无关的s列表,只需使用List<Node>
. 否则,您将需要找出将节点添加到 DOM 树的位置并使用常规方法。
UPDATE: I didn't notice you were declaring the NodeList
- this won't work unless you implement it yourself as Perry Monschau says. Just use List<Node>
instead.
更新:我没有注意到你在声明NodeList
- 这不会起作用,除非你像 Perry Monschau 所说的那样自己实现它。换用就好了List<Node>
。