1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public static void addxml()
{Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
File baseDir = new File(new);
File f = new File(baseDir+".xml");
if(f.exists()) System.out.println("true");
StreamResult result=new StreamResult(f);
DOMSource source =new DOMSource(document);
//creation de l element racine Application
Element application = (Element) document.createElement("famille");
//on le place dans l'arbre
document.appendChild(application);
Element xinterface=document.createElement("pere");
xinterface.setAttribute("nom","p");
xinterface.setAttribute("preneom","pp");
xinterface.setAttribute("naissance","out");
Element fils=document.createElement("fils");
fils.setAttribute("nom","p1");
fils.setAttribute("prenom","pp1");
fils.setAttribute("naissance","decembre");
Element mere=document.createElement("fils");
mere.setAttribute("nom","m1");
mere.setAttribute("prenom","mm1");
mere.setAttribute("naissance","decembre");
xinterface.appendChild(fils);
xinterface.appendChild(mere);
application.appendChild(xinterface);
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD,"xml");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no");
transformer.transform(source,result);
}
catch (TransformerConfigurationException e) {
System.out.println(e.getMessage());
}}
catch(Exception g) {
System.out.println(g.getMessage());
}} |
Partager