Java:如何用包装所有元素在 org.w3c.dom 中?
我的目标是用标签
public static void main(String[] args){
org.w3c.dom.DOMDocument doc;
paintAllNodes(doc, 0);
}
public static void paintAllNodes(Node node, int level) {
// Process node
// If there are any children, visit each one
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
// Get child node
Node childNode = list.item(i);
// Visit child node
paintAllNodes(childNode, level+1);
}
}
My goal is to wrap every single dom elements (Node.ELEMENT_NODE
) on current org.w3c.dom.Document
with tag <something style="background-color:red"></something>
.
public static void main(String[] args){
org.w3c.dom.DOMDocument doc;
paintAllNodes(doc, 0);
}
public static void paintAllNodes(Node node, int level) {
// Process node
// If there are any children, visit each one
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
// Get child node
Node childNode = list.item(i);
// Visit child node
paintAllNodes(childNode, level+1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
解决此类问题(对于任何 XML 转换)最简单的方法之一是使用 XSLT。
此 XSLT 转换:
当应用于任何 XML 文档时,例如这个:
产生所需的正确结果:
注意:留给读者练习如何在 Java 代码中启动 XSLT 转换:)
One of the simplest ways to solve such kind of problems (as for any XML transformation) is by using XSLT.
This XSLT transformation:
when applied on any XML document, for example this one:
produces the wanted, correct result:
Note: It is left as an exercise to the reader how to initiate an XSLT transformation in Java code :)
这会将每个
Node.ELEMENT_NODE
包装在org.w3c.dom.Document
中,并带有
标记:如果您想排除然后在第一个
for
循环中将所有节点过滤掉。This will wrap every
Node.ELEMENT_NODE
in aorg.w3c.dom.Document
with a<something>
tag:If you want to exclude any nodes then just filter them out in the first
for
loop.我想向您建议一个递归解决方案,它利用
Node#replaceChild
方法用新标签替换节点:这是我的主要:
我已经使用此 xml 对其进行了测试:
我的main 已打印出这个新的 xml,这似乎就是您想要的:
希望这会有所帮助。
I'd like to propose you a recursive solution, which make use of
Node#replaceChild
method to replace a node with a new tag:This is my main:
I've tested it with this xml:
My main has printed out this new xml, which seems to be what you want:
Hope this helps.
作为非答案;-)我建议使用 CSS...
something {background:red}
显然,只有当你使用 CSS 时这才有意义。
As a non-answer ;-) I propose to use CSS...
something {background:red}
Obviously, this only makes sense if you use CSS anyways.
对于任何给定的节点“node”,以及它来自类似的文档“document”,应该可以工作。
For any given node 'node', and the document 'document' it came from something like this should work.