I am new in Java and XML. I need to modify a part of this XML file using a Java program :
<?xml version="1.0" encoding="UTF-8"?>
<Traduction>
<Entrée>
<Word1>Word1</Word1>
<N1>0</N1>
<N2>0</N2>
<Word2>Word2</Word2>
</Entrée>
<Sortie>
<Word1>Word1</Word1>
<N1>0</N1>
<N2>0</N2>
<Word2>Word2</Word2>
</Sortie>
</Traduction>
I wanted to use this code in Eclipse :
try {
String filepath = "/home/user/Trad/ex1.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(filepath);
Node Traduction = document.getChildNodes().item(0);
Node Sortie = Traduction.getChildNodes().item(1);
Sortie.getChildNodes().item(0).setTextContent("AAA");
Sortie.getChildNodes().item(1).setTextContent("001");
Sortie.getChildNodes().item(2).setTextContent("002");
Sortie.getChildNodes().item(3).setTextContent("BBB");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
}
catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
catch (TransformerException tfe) {
tfe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
catch (SAXException sae) {
sae.printStackTrace();
}
But I get this result, which is not what I want :
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Traduction>
<Entrée>AAA<Word1>001</Word1>002<N1>BBB</N1>
<N2>0</N2>
<Word2>Word2</Word2>
</Entrée>
<Sortie>
<Word1>Word1</Word1>
<N1>0</N1>
<N2>0</N2>
<Word2>Word2</Word2>
</Sortie>
</Traduction>
I would like to get :
<?xml version="1.0" encoding="UTF-8"?>
<Traduction>
<Entrée>
<Word1>Word1</Word1>
<N1>0</N1>
<N2>0</N2>
<Word2>Word2</Word2>
</Entrée>
<Sortie>
<Word1>AAA</Word1>
<N1>001</N1>
<N2>002</N2>
<Word2>BBB</Word2>
</Sortie>
</Traduction>
What should I modify in my Java code to get this ?