/***** Code de MesExemples.com *******/ /** * @(#)XMLSetElements.java * * * @author *sakoba(java.mesexemples.com) @version 1.00 2013/7/5 */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class XMLSetElements { public static Element findElementElseCreateAndSet(Document document, Element parent, String child, String value) { Element ret = null; NodeList list_node = parent.getElementsByTagName(child); if (list_node.getLength() == 0) { parent.appendChild(document.createElement(child)); ret = (Element) parent.getElementsByTagName(child).item(0); ret.appendChild(document.createTextNode(value)); } return ret; } } |
Code testé avec le fichier XML Suivant
<?xml version="1.0" encoding="windows-1252"?> <!-- Edited by MesEXemple.com --> <note> <to>Sakoba</to> <from>Adams</from> <heading>Rappel</heading> <body>Ne m'oubliez pas ce week-end!</body> </note> |
Cet article Java XML: Créer et confiurer un élément s’il n’existe pas est apparu en premier sur .