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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReadWrite {
public static void main (String []args) {
try {
File file = new File("exemple.xml");
Document document = fileToDocument(file);
NodeList nodeList = document.getElementsByTagName("interface");
Node node = nodeList.item(0); // on suppose qu'il y a qu'un seul noeud interface
node.getAttributes().getNamedItem("longueur").setNodeValue("500");
node.getAttributes().getNamedItem("largeur").setNodeValue("500");
documentToFile(document, file);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Transforms a xml file into a DOM XML document.
*
* @param file
* The file to parse
* @return The DOM XML document
*/
public static Document fileToDocument(File file) throws Exception {
InputStreamReader converter = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
Source xmlSource = new StreamSource(converter);
Result xmlResult = new DOMResult();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(xmlSource, xmlResult);
converter.close();
return (Document) ((DOMResult) xmlResult).getNode();
}
/**
* Transforms a DOM XML document into xml file.
*
* @param document
* The DOM XML document
* @param file
* The output file
*/
public static void documentToFile(Document document, File file) throws Exception {
StreamResult xmlfile = new StreamResult(file);
/* Serialization */
DOMSource domSource = new DOMSource(document);
TransformerFactory transformFactory = TransformerFactory.newInstance();
Transformer serializer = transformFactory.newTransformer();
/* final step */
serializer.transform(domSource, xmlfile);
}
} |
Partager