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
| public class CreateJdomFromSax {
private static String xmlSource = "EA_v16_1.xmi";
private static Document document;
private static Element racine;
public static void main(String[] args) throws JDOMException, IOException {
document = getDoc(xmlSource);
// The root element is the root of the document. we print its name
System.out.println(document.getRootElement().getName());
//racine = document.getRootElement().getChild("XMI.content").getChild("XMI.Model").getChild("UML:Namespace.ownedElement"); <- ne fonctionne pas ...
racine = document.getRootElement().getChild("XMI.content");
Element model = racine.getChild("XMI.Model"); //model = null
Element owned = model.getChild("UML:Namespace.ownedElement"); //comme model était égal à null précédemment, j'obtiens ici une ex
List<Element> listPackages = racine.getChildren("UML:Package");
for(Element pack : listPackages){
System.out.println(pack.getName());
}
}//main
private static Document getDoc(String sourceFile) {
SAXBuilder jdomBuilder = new SAXBuilder();
Document doc = null;
// jdomDocument is the JDOM2 Object
try {
doc = jdomBuilder.build(new File(sourceFile));
} catch (JDOMException | IOException e) {e.printStackTrace();}
return doc;
}//getDoc
private static void enregistre(String fichier){
XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
//Remarquez qu'il suffit simplement de créer une instance de FileOutputStream
//avec en argument le nom du fichier pour effectuer la sérialisation.
try {
sortie.output(document, new FileOutputStream(fichier));
} catch (IOException e) {e.printStackTrace();}
}// enregistre
private static void affiche() {
XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
try {
sortie.output(document, System.out);
} catch (IOException e) {e.printStackTrace();}
}//affiche
} |