我想用Java重命名XML的根节点。 我尝试了各种解决方案,但没有一种方法有效。
我的代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File xmlFile = new File("C:/test.xml");
Document doc = builder.parse(new FileInputStream(xmlFile));
File xmiFile = new File("C:/test.xmi");
FileMover.copyFile(xmlFile, xmiFile);
Document doc2 = builder.parse(new FileInputStream(xmiFile));
doc2.importNode(doc.getDocumentElement(), true);
doc2.getElementsByTagName("report");
Node reportNode = doc2.getDocumentElement();
Element reportElement = (Element) reportNode;
doc2.renameNode(reportElement, "reports.dtd", "report:ReportType");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Source source2 = new DOMSource(doc2.getDocumentElement());
StringWriter out = new StringWriter();
Result result2 = new StreamResult(out);
transformer.transform(source2, result2);
运行代码,我得到以下异常: 线程中的异常"主线程" org.w3c.dom.DOMException:HIERARCHY_REQUEST_ERR:尝试插入不允许的节点。 at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(CoreDocumentImpl.java:392) at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.renameNode(CoreDocumentImpl.java:1047) 在XMIConverter.main(XMIConverter.java:57)