JDOM
{{howto|date=May 2011}}
{{Infobox Software
| name = JDOM
| caption =
| developer =
| latest release version = 2.0.6.1
| latest release date = {{release date|2021|12|09}}
| operating system = Cross-platform
| programming language = Java
| genre = XML binding
| license = Similar to Apache License
| website = {{URL|http://jdom.org}}
}}
JDOM is an open-source Java-based document object model for XML that was designed specifically for the Java platform so that it can take advantage of its language features.{{Cite web |title=JDOM |url=https://mvnrepository.com/artifact/org.jdom/jdom |access-date=October 14, 2024 |website=Maven Repository}} JDOM integrates with Document Object Model (DOM) and Simple API for XML (SAX), supports XPath and XSLT.{{Cite web |title=How to read XML file in Java – (JDOM Parser) |url=https://mkyong.com/java/how-to-read-xml-file-in-java-jdom-example/ |access-date=October 14, 2024 |website=Mkyong.com|date=21 December 2009 }} It uses external parsers to build documents. JDOM was developed by Jason Hunter and Brett McLaughlin starting in March 2000.{{Cite web |title=artima - A Design Review of JDOM |url=https://www.artima.com/articles/a-design-review-of-jdom |access-date=2024-10-14 |website=www.artima.com}} It has been part of the Java Community Process as JSR 102, though that effort has since been abandoned.{{Cite web |title=The Java Community Process(SM) Program - JSRs: Java Specification Requests - detail JSR# 102 |url=https://www.jcp.org/en/jsr/detail?id=102 |access-date=2024-10-14 |website=www.jcp.org}}
Examples
Suppose the file "foo.xml" contains this XML document:
One can parse the XML file into a tree of Java objects with JDOM, like so:
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new FileInputStream("foo.xml"));
Element root = doc.getRootElement();
// root.getName() is "shop"
// root.getAttributeValue("name") is "shop for geeks"
// root.getAttributeValue("location") is "Tokyo, Japan"
// root.getChildren() is a java.util.List object that contains 3 Element objects.
In case you do not want to create the document object from any file or any input stream, you can create the document object against the element.
Element root = new Element("shop"); // here
Document doc = new Document(root); // create a new document with the supplied element as the root
As a converse, one can construct a tree of elements, then generate an XML file from it, as in the following example:
Element root = new Element("shop");
root.setAttribute("name", "shop for geeks");
root.setAttribute("location", "Tokyo, Japan");
Element item1 = new Element("computer");
item1.setAttribute("name", "iBook");
item1.setAttribute("price", "1200$");
root.addContent(item1);
// perform similar steps for other elements
XMLOutputter outputter = new XMLOutputter();
outputter.output(new Document(root), new FileOutputStream ("foo2.xml"));
References
{{reflist}}