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
|
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import java.io.FileWriter;
import java.io.IOException;
public class JDomCreatingXml {
public static void main(String[] args) {
Document document = new Document();
Element root = new Element("Graph");
//
// Creating a child for the root element. Here we can see how to
// set the text of an xml element.
//
Element child = new Element("Node");
child.setAttribute("key", "x");
child.addContent(new Element("X").setText("30"));
child.addContent(new Element("Y").setText("40"));
child.addContent(new Element("Name").setText("MASG"));
Element child2 = new Element("edge");
child2.setAttribute("key", "y");
child2.addContent(new Element("target").setText("n1"));
child2.addContent(new Element("source").setText("n2"));
child2.addContent(new Element("Name").setText("FH"));
//
// Add the child to the root element and add the root element as
// the document content.
//
root.addContent(child);
child.addContent(child2);
document.setContent(root);
try {
FileWriter writer = new FileWriter("Graph.xml");
XMLOutputter outputter = new XMLOutputter();
//
// Set the XLMOutputter to pretty formatter. This formatter
// use the TextMode.TRIM, which mean it will remove the
// trailing white-spaces of both side (left and right)
//
outputter.setFormat(Format.getPrettyFormat());
//
// Write the document to a file and also display it on the
// screen through System.out.
//
outputter.output(document, writer);
outputter.output(document, System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
} |
Partager