java - 转换整个 dom4j 元素的命名空间
问题描述
如果我有这样的 XML 元素:
<First id="" name="">
<Second id="" name="">
</Second>
</First>
如何使用 dom4j 将命名空间转换为类似下面的内容?有简单的方法吗?
<test:First test:id="" test:name="">
<test:Second test:id="" test:name="">
</test:Second>
</test:First>
解决方案
如果您更喜欢以 Java 为中心的解决方案,DOM4J 支持遍历文档树:
Document doc = DocumentHelper.parseText(XML);
final Namespace ns = Namespace.get("test", "urn:foo:bar");
doc.accept(new VisitorSupport() {
@Override
public void visit(Element node) {
node.setQName(QName.get(node.getName(), ns));
// Attribute QNames are read-only, so need to create new
List<Attribute> attributes = new ArrayList<Attribute>();
while(node.attributes().size() > 0)
attributes.add(node.attributes().remove(0));
for(Attribute a: attributes) {
node.addAttribute(QName.get(a.getName(), ns), a.getValue());
}
}
});