在 Java 中重命名所有 XML 标记名称 [英] Renaming all XML tag names in Java
问题描述
我有一个带有这样前缀的 XML 文件:
I have an XML file with the prefix like this one:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
我想重命名移动冒号的前缀以支持破折号,因此:
I want to rename the prefix moving the colon in favour of the dash, so:
<h-table>
<h-tr>
<h-td>Apples</h:td>
<h-td>Bananas</h:td>
</h-tr>
</h-table>
<f-table>
<f-name>African Coffee Table</f:name>
<f-width>80</f:width>
<f-length>120</f:length>
</f-table>
使用 DOM 解析器我知道可以按名称获取元素,但在我的情况下,我需要将它们全部应用重命名,因为模式始终相同.
Using the DOM parser I know that is possible to get elements by name, but in my case I need to take them all applying the renaming since the pattern is always the same.
现在这个函数我要写无数遍了,因为一个只为一个标签:
Now I have to write this function countless times, because one is just for one tag:
NodeList nodes = document.getElementsByTagName("h:table");
for (Node eachNode: nodes) {
document.renameNode(eachNode, null, "h-table");
}
是否可以使用更通用的方法?
Is it possible to use a more general approach?
推荐答案
您可以像这样递归遍历和重命名 DOM 元素:
You can traverse and rename DOM elements recursively like this:
private static void renameElement(Document document, Element element) {
document.renameNode(element, null, element.getNodeName().replace(':', '-'));
NodeList children = element.getChildNodes();
for(int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element) {
renameElement(document, (Element) child);
}
}
}
从根元素开始递归:
renameElement(document, document.getDocumentElement());
但是,您应该考虑是否真的要破坏 XML 命名空间-好吧-形成的一致性.好吧,它仍然是一致的,但你失去了元素命名空间绑定.
However, you should consider if you really want to break XML namespace-well-formed conformance. Okay, it is still conformant but you lose element namespace binding.
这篇关于在 Java 中重命名所有 XML 标记名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!