Renaming all XML tag names in Java

做~自己de王妃 提交于 2019-12-26 00:17:26

问题


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>

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?


回答1:


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);
        }

    }
}

Start recursion from the root element:

renameElement(document, document.getDocumentElement());

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.




回答2:


You can always fall back to pain old text processing, you know. Just search and replace regex pattern. search for

<([^:]*):(.*)>

and replace with <$1-$2> for starting tags.

If you have to do this in java, there is java.util.regex package. But sed rocks for such tasks.



来源:https://stackoverflow.com/questions/52260440/renaming-all-xml-tag-names-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!