我有这个XML文件:
<tomcat-users>
<role rolename="manager"/>
<role rolename="admin"/>
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcxat" roles="role1"/>
<user username="ide" password="1234" roles="manager,admin"/>
<user username="hainn" password="hainn" roles="manager,admin"/>
</tomcat-users>
我必须像这样放置并成为父节点:
<tomcat-users>
<roles>
<role rolename="manager"/>
<role rolename="admin"/>
<role rolename="tomcat"/>
<role rolename="role1"/>
</roles>
<users>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcxat" roles="role1"/>
<user username="ide" password="1234" roles="manager,admin"/>
<user username="hainn" password="hainn" roles="manager,admin"/>
</users>
</tomcat-users>
我尝试使用此代码:
public static void main(String[] args) {
// TODO code application logic here
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File f = new File("tomcat-users.xml");
Document doc = db.parse(f);
addParentNode(doc);
writeXML(doc,f);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void writeXML(Document doc, File f) {
try {
Source source = new DOMSource(doc);
Result result = new StreamResult(f);
TransformerFactory transform = TransformerFactory.newInstance();
Transformer trans = transform.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no");
trans.setOutputProperty(OutputKeys.INDENT,"yes");
StreamResult rs = new StreamResult(new File("newTomcat.xml"));
DOMSource dom = new DOMSource(doc);
trans.transform(dom, rs);
System.out.println("Finish");
} catch (Exception e) {
e.printStackTrace();
}
}
问题是我不知道如何写addParentNode
。我应该appendChild()
使用getFirstChild()
吗?
请给我一个示例代码,我真的很感激。非常感谢你......