使用 JDOM 重写 XML/DOM 树时出现问题 (ConcurrentModificationException)

发布于 2024-07-13 19:18:14 字数 396 浏览 5 评论 0原文

我需要遍历 JDOM 树并在进行时进行更改; 此时,更改主要是添加新元素,但也可能包括重新排序元素或删除元素。 所有工作都在同一个线程上完成,因此不存在并发问题。

事实证明这很困难,因为如果您尝试在遍历期间添加节点,JDOM 迭代器可能会抛出 ConcurrentModificationException。 据我所知,JDOM 使用列表而不是直接链接 DOM 节点,这使得动态修改变得困难。

我看到了一些关于如何处理这个问题的建议,例如将添加推迟到遍历完成之后,或者动态构建一棵新树以使遍历的树保持不变。 这些对我不起作用,因为我在修改树时需要一致的视图。

我开始怀疑 JDOM 在这里不起作用。 其他 Java DOM 模型是否能让这变得更容易? 或者有没有办法在 JDOM 中做到这一点?

I need to walk a JDOM tree and make changes as I go along; at this point, changes are mostly adding new elements right now but could also include reordering elements or removing elements. All work is done on the same thread so there are no concurrency issues.

This turns out to be difficult because JDOM iterators can throw a ConcurrentModificationException if you try to add a node during traversal. From what I can see, JDOM uses lists instead of directly linking DOM nodes and this makes it difficult to do modifications on the fly.

I've seen a couple of recommendations on how to deal with this, such as deferring the adds until after the traversal is done, or building a new tree on the fly so that the traversed tree remains unchanged. These won't work for me because I need a consistent view of the tree as I modify it.

I'm beginning to suspect that JDOM just won't work here. Do any of the other Java DOM models make this easier? Or is there a way to do this in JDOM?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一身软味 2024-07-20 19:18:14

我使用 JDOM 提出了一个看起来简单的解决方案。 我没有直接使用 JDOM 迭代器,而是使用迭代器创建节点列表,然后使用该列表进行遍历。 由于此列表不是“实时”的,因此我的脚本可以修改树(并查看更改)而不影响遍历。 遍历不会看到结构变化,但这应该不是问题。

I've come up with what looks like an easy solution using JDOM. Rather than using the JDOM iterator directly, I use the iterator to create a list of nodes and then traverse using this list. Since this list is not "live", my scripts can modify the tree (and see the changes) without affecting the traversal. The traversal won't see structural changes but that should not be a problem.

孤凫 2024-07-20 19:18:14

有什么理由不能简单地进行两次传递吗?

我熟悉的大多数算法在装饰一棵树时不需要超过 2 次遍历(理想情况下,您的算法应该需要一次初始装饰,也许需要第二次来解决装饰后的引用)。

Is there a reason you can't simply do two passes?

Most algorithms I'm familiar with won't require more than 2 traversals when decorating a tree (ideally, your algorithm should need a pass for initial decoration and perhaps a second for resolving references after the decoration).

请爱~陌生人 2024-07-20 19:18:14

由于您愿意使用其他模型,因此您可以考虑 Elliotte Rusty Harold 的 XOM API。 它坚如磐石,不允许您创建无效的 XML 结构。

Since you are open to using other models, you might consider Elliotte Rusty Harold's XOM API. It's rock solid, and won't allow you to create an invalid XML structure.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文