Java/XML/JDOM
Содержание
- 1 Accessing Attributes Using JDOM
- 2 Add elements to root element
- 3 Adding an Attribute Using JDOM
- 4 Adding an Element Using JDOM
- 5 Create document from jdom
- 6 Creating a Document Using JDOM
- 7 extends org.jdom.Element
- 8 General XML Utility Functions For JDOM
- 9 Get child from root
- 10 Iterate through elements
- 11 JDom: Locating a speech with the findCharactersFirstSpeech() method
- 12 JDOM: transform
- 13 JDOM Util
- 14 List an XML file after building it into a JDOM Document
- 15 Make up and write an XML document, using JDOM
- 16 NamespaceTest with JDOM
- 17 Outputting a Document Using XMLOutputter
- 18 Parsing with JDOM
- 19 Read an XML document using JDOM
- 20 Simple demo of JDOM
- 21 Simple example of using JDOM
- 22 Use JDOM to build a document
- 23 Use JDOM to change the element text
- 24 Use SAXBuilder from JDOM
- 25 Use Unchecked JDOM Factory
- 26 Use XPath in servlet
- 27 XPath with JDOM
Accessing Attributes Using JDOM
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.adapters.XercesDOMAdapter;
import org.jdom.input.DOMBuilder;
public class JDOMCreateExample {
private static DOMBuilder builder = null;
public static void main(String args[]) throws Exception, FileNotFoundException {
XercesDOMAdapter xercAdapter = new XercesDOMAdapter();
org.w3c.dom.Document w3Dom = xercAdapter.getDocument(new FileInputStream("games.xml"), false);
builder = new DOMBuilder("org.jdom.adapters.XercesDOMAdapter");
Document doc = builder.build(w3Dom);
List childs = doc.getRootElement().getChildren("game");
Iterator itr = childs.iterator();
while (itr.hasNext()) {
Element child = (Element) itr.next();
System.out.println(child.getName() + " = " + child.getText());
System.out.println(child.getAttributeValue("genre"));
}
}
}
Add elements to root element
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class MainClass {
public static void main(String[] args) throws Exception {
Element rootElement = new Element("root");
Document document = new Document(rootElement);
for (int i = 0; i < 10000; i++) {
rootElement.addContent(new Element("blah"));
rootElement.addContent(new Element("blah"));
rootElement.addContent(new Element("blah").setText("foo"));
rootElement.addContent(new Element("blah"));
}
new XMLOutputter().output(document, System.out);
}
}
Adding an Attribute Using JDOM
import org.jdom.Document;
import org.jdom.Element;
public class MainClass {
public static void main(String args[]) {
Document doc = new Document(new Element("games"));
Element newGame = new Element("game").setText("Final Fantasy");
doc.getRootElement().addContent(newGame);
newGame.setAttribute("genre", "rpg");
}
}
Adding an Element Using JDOM
import org.jdom.Document;
import org.jdom.Element;
public class MainClass {
public static void main(String args[]) {
Document doc = new Document(new Element("games"));
Element newGame = new Element("game").setText("Final Fantasy");
doc.getRootElement().addContent(newGame);
}
}
Create document from jdom
import java.io.IOException;
import org.jdom.rument;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class MainClass {
public static void main(String[] args) throws IOException {
Document doc = new Document(new Element("r").setAttribute("attribute", "value").addContent(
new Element("inner")).addContent(new Comment("comment text"))
.addContent("some inline text").addContent(new Element("inner2")));
new XMLOutputter(Format.getPrettyFormat()).output(doc, System.out);
}
}
Creating a Document Using JDOM
import org.jdom.Document;
import org.jdom.Element;
public class MainClass {
public static void main(String args[]) {
Document doc = new Document(new Element("games"));
}
}
extends org.jdom.Element
import org.jdom.Element;
import org.jdom.Namespace;
public class ORAElement extends Element {
private static final Namespace ORA_NAMESPACE =
Namespace.getNamespace("ora", "http://www.jexp.ru");
public ORAElement(String name) {
super(name, ORA_NAMESPACE);
}
public ORAElement(String name, Namespace ns) {
super(name, ORA_NAMESPACE);
}
public ORAElement(String name, String uri) {
super(name, ORA_NAMESPACE);
}
public ORAElement(String name, String prefix, String uri) {
super(name, ORA_NAMESPACE);
}
}
General XML Utility Functions For JDOM
package net.firstpartners.nounit.utility;
/**
* Title: NoUnit - Identify Classes that are not being unit Tested
*
* Copyright (C) 2001 Paul Browne , FirstPartners.net
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* @author Paul Browne
* @version 0.6
*/
import java.io.*;
import java.util.*;
import java.util.zip.*;
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
/**
* General XML Utility Functions
*/
public class XmlUtil {
/**
* indexes the nodes in the document that is passed in , via a HashMap mapping
* mapping is in the format <index> as String , handle to <element> of node<BR>
* Strings are used as they are better lookup in the hashmap.
* @param inXmlDocument to generated the hashmap from
* @param uniqueAttribute to do the index on (i.e. key in HashMap). Examples
* of uniqueAttributes are id"s or names.
* @return HashMap containing mappings
*/
public static HashMap getNodeIndex(Document inXmlDocument,
String uniqueAttribute) {
//Internal Variables
int stackPointer=0;
String locationId =null;
Attribute tmpAttribute=null;
Element thisElement=null;
ListIterator deepestList=null;
HashMap mappings = new HashMap();
List stack = new Vector();
//Get the list information for the entire document
stack.add(inXmlDocument.getContent().listIterator());
//Loop though the elements on list
while (!stack.isEmpty()){
//Get the last list on the stack
deepestList = (ListIterator)stack.get(stack.size()-1);
//Does this list have more elements?
if (deepestList.hasNext()) {
//if so Get Next element from this list
thisElement = (Element)deepestList.next();
//Add Mapping for this element to hashtable
tmpAttribute = thisElement.getAttribute(uniqueAttribute);
//Attibute can be null for non folder elements (e.g. root element) - if so ignore
if (tmpAttribute!=null) {
locationId= tmpAttribute.getValue();
if ((locationId!=null)&&(locationId!="")) {
mappings.put(locationId.toString(),thisElement);
}
} //end add mapping
//does this list have children ?
if(thisElement.hasChildren()){
//if so add to the stack
stackPointer++;
stack.add(thisElement.getChildren().listIterator());
}
}
else
{
//if not , remove this list from the stack
stack.remove(stackPointer);
stackPointer--;
} // end if stack has more elements
}
return mappings;
}
/**
* gets all elements in the XML Document Being Passed in <BR>
* @param inXmlDocument to generated the hashmap from
* @return nodeList containing nodes
*/
public static HashSet getAllNodes(Document inXmlDocument) {
//Internal Variables
int stackPointer=0;
int index=1;
String locationId=null;
Element currentElement=null;
Element parentElement=null;
Element thisElement=null;
Attribute tmpAttribute=null;
List elementList=null;
ListIterator deepestList=null;
HashMap mappings = new HashMap();
HashSet nodeList = new HashSet();
List stack = new Vector(); //Implements list interface
//Get the list information for the entire document - kick start loop
stack.add(inXmlDocument.getContent().listIterator());
//Loop though the elements on list
while (!stack.isEmpty()){
//Get the last list on the stack
deepestList = (ListIterator)stack.get(stack.size()-1);
//Does this list have more elements?
if (deepestList.hasNext()) {
//if so Get Next element from this list
thisElement = (Element)deepestList.next();
// add this element to the list
nodeList.add(thisElement);
//does this list have children ?
if(thisElement.hasChildren()){
//if so add to the stack
stackPointer++;
stack.add(thisElement.getChildren().listIterator());
}
}
else
{
//if not , remove this list from the stack
stack.remove(stackPointer);
stackPointer--;
} // end if stack has more elements
}
return nodeList;
}
/**
* Search for Nodes within Jdom Document<BR>
* @param inDocumentToSearch XML-JDOM Document
* @param uniqueIdentifierName we can use to index the document (unique
* attribute like id or name present on the node we are searching for)
* @param uniqueIdentifierToFind in the indexed document
*/
public static Element findNode(Document inDocumentToSearch
, String uniqueIdentifierName
, String uniqueIdentifierToFind) {
// index document
HashMap index = getNodeIndex(inDocumentToSearch,
uniqueIdentifierName);
// Now get required element from index
return (Element)index.get(uniqueIdentifierToFind);
}
}
Get child from root
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class MainClass {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document books = builder.build("books.xml");
Document onebook = builder.build("onebook.xml");
Element bookToAdd = onebook.getRootElement().getChild("book");
books.getRootElement().addContent(bookToAdd);
new XMLOutputter(Format.getPrettyFormat()).output(books, System.out);
}
}
Iterate through elements
import java.util.Iterator;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
public class MainClass {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build("mixed.xml");
for (Iterator it = doc.getRootElement().getContent().iterator(); it.hasNext();) {
Content content = (Content) it.next();
if (content instanceof Text) {
System.out.println("[Text: " + ((Text) content).getTextNormalize());
} else {
System.out.println(content.toString());
}
}
}
}
JDom: Locating a speech with the findCharactersFirstSpeech() method
import java.io.File;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class MainClass {
public static void main(String[] args) throws Exception{
String characterName ="asdf";
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("r.xml"));
List actList = document.getRootElement().getChildren("ACT");
allDone: for (int act = 0; act < actList.size(); act++) {
List sceneList = ((Element) actList.get(act)).getChildren("SCENE");
for (int scene = 0; scene < sceneList.size(); scene++) {
List speechList = ((Element) sceneList.get(scene)).getChildren("SPEECH");
for (int speech = 0; speech < speechList.size(); speech++) {
if (characterName.equalsIgnoreCase(((Element) speechList.get(speech))
.getChildText("SPEAKER"))) {
System.out.println(characterName);
break allDone;
}
}
}
}
}
}
JDOM: transform
import java.io.File;
import java.io.FileWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.jdom.transform.JDOMResult;
import org.jdom.transform.JDOMSource;
public class Transform2 {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("r.xml"));
Transformer transformer = TransformerFactory.newInstance().newTransformer(
new StreamSource("program.xsl"));
JDOMResult out = new JDOMResult();
transformer.transform(new JDOMSource(document), out);
XMLOutputter xmlOutputter = new XMLOutputter();
xmlOutputter.output(out.getDocument(), new FileWriter("JDOMAlteredRichard.html"));
}
}
JDOM Util
/*
* This file is made available under the terms of the LGPL licence.
* This licence can be retrieved from http://www.gnu.org/copyleft/lesser.html.
* The source remains the property of the YAWL Foundation. The YAWL Foundation is a
* collaboration of individuals and organisations who are committed to improving
* workflow technology.
*/
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.*;
import org.apache.log4j.Logger;
import java.io.*;
/**
* Some static utility methods for coverting JDOM Documents and Elements
* to Strings and files & vice versa.
*
* @author Michael Adams
* 04/07/2006
*
* Last date: 22/06/08
*/
public class JDOMUtil {
private static Logger _log = Logger.getLogger("org.yawlfoundation.yawl.util.JDOMUtil");
/****************************************************************************/
public static String documentToString(Document doc) {
if (doc == null) return null;
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
return out.outputString(doc);
}
/****************************************************************************/
public static String elementToString(Element e) {
if (e == null) return null ;
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
return out.outputString(e);
}
/****************************************************************************/
public static String elementToStringDump(Element e) {
if (e == null) return null ;
XMLOutputter out = new XMLOutputter(Format.getCompactFormat());
return out.outputString(e);
}
/****************************************************************************/
public static Document stringToDocument(String s) {
try {
if (s == null) return null ;
return new SAXBuilder().build(new StringReader(s));
}
catch (JDOMException jde) {
_log.error("JDOMException converting to Document, String = " + s , jde);
return null ;
}
catch (IOException ioe) {
_log.error("IOException converting to Document, String = " + s, ioe);
return null ;
}
}
/****************************************************************************/
public static Element stringToElement(String s) {
if (s == null) return null ;
Document doc = stringToDocument(s);
return doc.getRootElement();
}
/****************************************************************************/
public static Document fileToDocument(String path) {
try {
if (path == null) return null ;
return new SAXBuilder().build(new File(path));
}
catch (JDOMException jde) {
_log.error("JDOMException loading file into Document, filepath = " + path , jde);
return null ;
}
catch (IOException ioe) {
_log.error("IOException loading file into Document, filepath = " + path, ioe);
return null ;
}
}
/****************************************************************************/
/** saves a JDOM Document to a file */
public static void documentToFile(Document doc, String path) {
try {
FileOutputStream fos = new FileOutputStream(path);
XMLOutputter xop = new XMLOutputter(Format.getPrettyFormat());
xop.output(doc, fos);
fos.flush();
fos.close();
}
catch (IOException ioe){
_log.error("IO Exeception in saving Document to file, filepath = " + path, ioe) ;
}
}
/****************************************************************************/
public static String getDefaultValueForType(String dataType) {
if (dataType == null) return "null";
else if (dataType.equalsIgnoreCase("boolean")) return "false" ;
else if (dataType.equalsIgnoreCase("string")) return "" ;
else return "0";
}
/****************************************************************************/
public static String encodeEscapes(String s) {
if (s == null) return s;
return s.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("\"", """)
.replaceAll(""", "'") ;
}
public static String decodeEscapes(String s) {
if (s == null) return s;
return s.replaceAll("&", "&")
.replaceAll("<","<")
.replaceAll(">", ">")
.replaceAll(""","\"")
.replaceAll("'", """) ;
}
/****************************************************************************/
public static String formatXMLString(String s) {
if (s == null) return null;
if (s.startsWith("<?xml"))
return documentToString(stringToDocument(s));
else
return elementToString(stringToElement(s));
}
public static String formatXMLStringAsDocument(String s) {
return documentToString(stringToDocument(s));
}
public static String formatXMLStringAsElement(String s) {
return elementToString(stringToElement(s));
}
} //ends
List an XML file after building it into a JDOM Document
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.File;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
/**
* List an XML file after building it into a JDOM Document.
* Notice it is easier than using SAX or DOM directly.
*/
public class JDOMLister {
public static void main(String[] args) {
try {
SAXBuilder b = new SAXBuilder(true); // true -> validate
// Create a JDOM document.
Document doc = b.build(new File("people.xml"));
// Create an output formatter, and have it write the doc.
new XMLOutputter().output(doc, System.out);
} catch (JDOMException jex) {
System.out.print("PARSE ERROR: " + jex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// demo xml file
/*
<?xml version="1.0"?>
<people>
<person>
<name>Ian Darwin</name>
<email>http://www.darwinsys.ru/</email>
<country>Canada</country>
</person>
<person>
<name>Another Darwin</name>
<email type="intranet">afd@node1</email>
<country>Canada</country>
</person>
</people>
*/
Make up and write an XML document, using JDOM
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
/** Make up and write an XML document, using JDOM
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: DocWriteJDOM.java,v 1.4 2004/02/09 03:34:10 ian Exp $
*/
public class DocWriteJDOM {
public static void main(String[] av) throws Exception {
DocWriteJDOM dw = new DocWriteJDOM();
Document doc = dw.makeDoc();
// Create an output formatter, and have it write the doc.
new XMLOutputter().output(doc, System.out);
}
/** Generate the XML document */
protected Document makeDoc() throws Exception {
Document doc = new Document(new Element("Poem"));
doc.getRootElement().
addContent(new Element("Stanza").
addContent(new Element("Line").
setText("Once, upon a midnight dreary")).
addContent(new Element("Line").
setText("While I pondered, weak and weary")));
return doc;
}
}
// demo xml file
/*
<?xml version="1.0"?>
<people>
<person>
<name>Ian Darwin</name>
<email>http://www.darwinsys.ru/</email>
<country>Canada</country>
</person>
<person>
<name>Another Darwin</name>
<email type="intranet">afd@node1</email>
<country>Canada</country>
</person>
</people>
*/
NamespaceTest with JDOM
import java.io.File;
import java.io.FileOutputStream;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class MainClass {
public static void main(String[] args) throws Exception {
Namespace nsShort = Namespace.getNamespace("short");
Namespace nsWeird = Namespace.getNamespace("e", "w");
Document doc = new Document();
Element easy = new Element("easy", nsShort);
doc.setRootElement(easy);
Element b = new Element("b", nsShort);
Element c = new Element("c", nsShort);
easy.addContent(b);
b.addContent(c);
Element d = new Element("d", nsShort);
Element f = new Element("f", nsWeird);
f.addContent(new Element("g", nsShort));
d.addContent(f);
easy.addContent(d);
new XMLOutputter(Format.getPrettyFormat()).output(doc, new FileOutputStream("short.xml"));
SAXBuilder sb = new SAXBuilder();
sb.setFeature("http://xml.org/sax/features/namespaces", false);
sb.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
Document doc2 = sb.build(new File("short.xml"));
new XMLOutputter(Format.getPrettyFormat()).output(doc2, System.out);
}
}
Outputting a Document Using XMLOutputter
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class MainClass {
public static void main(String args[]) throws IOException {
Document doc = new Document(new Element("games"));
Element newGame = new Element("game").setText("Final Fantasy");
doc.getRootElement().addContent(newGame);
newGame.setAttribute("genre", "rpg");
XMLOutputter domstream = new XMLOutputter();
domstream.output(doc, System.out);
}
}
Parsing with JDOM
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.adapters.XercesDOMAdapter;
import org.jdom.input.DOMBuilder;
import org.jdom.output.XMLOutputter;
public class JDOMCreateExample {
private static DOMBuilder builder = null;
public static void main(String args[]) throws IOException, FileNotFoundException {
XercesDOMAdapter xercAdapter = new XercesDOMAdapter();
org.w3c.dom.Document w3Dom = xercAdapter.getDocument(new FileInputStream("games.xml"), false);
builder = new DOMBuilder("org.jdom.adapters.XercesDOMAdapter");
Document doc = builder.build(w3Dom);
}
}
Read an XML document using JDOM
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) {
String data = "<root><row><column name="username" length="6">admin</column>"
+ "<column name="password" length="1">p</column></row><row>"
+ "<column name="username" length="6">j</column>"
+ "<column name="password" length="8">q</column></row></root>";
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new ByteArrayInputStream(data.getBytes()));
Element root = document.getRootElement();
List rows = root.getChildren("row");
for (int i = 0; i < rows.size(); i++) {
Element row = (Element) rows.get(i);
List columns = row.getChildren("column");
for (int j = 0; j < columns.size(); j++) {
Element column = (Element) columns.get(j);
String name = column.getAttribute("name").getValue();
String value = column.getText();
int length = column.getAttribute("length").getIntValue();
System.out.println("name = " + name);
System.out.println("value = " + value);
System.out.println("length = " + length);
}
}
}
}
Simple demo of JDOM
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.rument;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.ProcessingInstruction;
import org.jdom.input.DOMBuilder;
import org.jdom.input.SAXBuilder;
import org.jdom.output.DOMOutputter;
/*
* Simple demo of JDOM
*/
public class JDOMDemo {
public static void main(String[] args) {
// Must be at least one file or URL argument
if (args.length == 0) {
System.out.println("Usage: java JDOMDemo URL [...]");
}
SAXBuilder saxBuilder = new SAXBuilder();
DOMBuilder domBuilder = new DOMBuilder();
for (int i = 0; i < args.length; i++) {
try {
Document jdomDocument = saxBuilder.build(args[i]);
DOMOutputter domOutputter = new DOMOutputter();
/*
* Test getting DOM Document from JDOM Document
org.w3c.dom.Document domDocument = domOutputter.output(doc);
*/
/*
* Test getting DOM Element from JDOM Element
*/
org.w3c.dom.Element domElement =
domOutputter.output(jdomDocument.getRootElement());
/*
* Test getting JDOM Element from DOM Element
*/
org.jdom.Element jdomElement = domBuilder.build(domElement);
demo(jdomElement);
} catch (JDOMException e) { // indicates a well-formedness or other error
System.out.println(args[i] + " is not a well formed XML document.");
System.out.println(e.getMessage());
} catch (IOException ex) {
System.out.println("Input or Output error:" +
args[i] + ": " + ex);
}
}
}
public static void demo(Document doc) {
List children = doc.getContent();
Iterator iterator = children.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o instanceof Element) {
demo((Element) o);
}
else if (o instanceof Comment)
doComment((Comment) o);
else if (o instanceof ProcessingInstruction)
doPI((ProcessingInstruction) o);
}
}
public static void demo(Element element) {
System.out.println("Element " + element);
List attributes = element.getAttributes();
List children = element.getContent();
Iterator iterator = children.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o instanceof Element) {
demo((Element) o);
}
else if (o instanceof Comment)
doComment((Comment)o);
else if (o instanceof ProcessingInstruction)
doPI((ProcessingInstruction)o);
else if (o instanceof String) {
System.out.println("String: " + o);
}
}
}
public static void doComment(Comment c) {
System.out.println("Comment: " + c);
}
public static void doPI(ProcessingInstruction pi) {
System.out.println("PI: " + pi);
}
}
// demo xml file
/*
<?xml version="1.0"?>
<people>
<person>
<name>Ian Darwin</name>
<email>http://www.darwinsys.ru/</email>
<country>Canada</country>
</person>
<person>
<name>Another Darwin</name>
<email type="intranet">afd@node1</email>
<country>Canada</country>
</person>
</people>
*/
Simple example of using JDOM
import java.util.Iterator;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
/**
* @author robh
*
*/
public class HelloPeopleJDOM {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build("./src/data.xml");
StringBuffer output = new StringBuffer();
// create the basic HTML output
output.append("<html>\n").append(
"<head>\n<title>\nPerson List</title>\n</head>\n").append(
"<body>\n").append("<ul>\n");
Iterator itr = doc.getRootElement().getChildren().iterator();
while (itr.hasNext()) {
Element elem = (Element) itr.next();
output.append("<li>");
output.append(elem.getAttribute("lastName").getValue());
output.append(", ");
output.append(elem.getAttribute("firstName").getValue());
output.append("</li>\n");
}
// create the end of the HTML output
output.append("</ul>\n</body>\n</html>");
System.out.println(output.toString());
}
}
Use JDOM to build a document
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import java.util.*;
import java.io.*;
public class JDOMTest {
public static void showBooks( Element root ) {
List books = root.getChildren( "book" );
for( Iterator i=books.iterator(); i.hasNext(); ) {
Element book = ( Element )i.next();
System.out.println( "Book: " + book.getAttributeValue( "category" ) + ", " +
book.getChildTextTrim( "title" ) + ", " +
book.getChildTextTrim( "author" ) + ", " +
book.getChildTextTrim( "price" ) );
}
}
public static void main( String[] args ) throws Exception{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build( "book.xml" );
Element root = doc.getRootElement();
System.out.println( "Book List Before: " );
showBooks( root );
// Add a new book
Element newBook = new Element( "book" );
newBook.setAttribute( "category", "fiction" );
Element newTitle = new Element( "title" );
newTitle.addContent( "Desecration" );
Element newAuthor = new Element( "author" );
newAuthor.addContent( "Tim LaHaye" );
Element newPrice = new Element( "price" );
newPrice.addContent( "19.95" );
newBook.addContent( newTitle );
newBook.addContent( newAuthor );
newBook.addContent( newPrice );
root.addContent( newBook );
System.out.println( "Book List After: " );
showBooks( root );
XMLOutputter out = new XMLOutputter( " ", true );
out.output( root, System.out );
}
}
<books>
<book category="fiction">
<title>title 1</title>
<author>Tim Lahaye</author>
<price>14.95</price>
</book>
<book category="science fiction">
<title>title 2</title>
<author>Tim Lahaye</author>
<price>14.95</price>
</book>
</books>
Use JDOM to change the element text
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class MainClass {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("r.xml"));
Element prologue, title, speech;
prologue = new Element("P");
List actList = document.getRootElement().getChildren("ACT");
document.getRootElement().removeChildren("ACT");
document.getRootElement().addContent(prologue);
for (int act = 0; act < actList.size(); act++) {
document.getRootElement().addContent((Element) actList.get(act));
}
title = new Element("TITLE");
title.setText("test");
prologue.addContent(title);
speech = new Element("SPEECH");
speech.setText("test");
prologue.addContent(speech);
XMLOutputter xmlOutputter = new XMLOutputter();
xmlOutputter.output(document, new FileWriter("rewrite.xml"));
}
}
Use SAXBuilder from JDOM
import java.util.Iterator;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class MainClass {
public static void main(String[] args) throws Exception {
Document doc = new SAXBuilder().build("books.xml");
Element books = doc.getRootElement();
Iterator it = books.getChildren().iterator();
while (it.hasNext()) {
Element book = (Element) it.next();
System.out.println(book.getChildText("name") + " was published in "
+ book.getChildText("pubDate"));
}
}
}
Use Unchecked JDOM Factory
import org.jdom.Document;
import org.jdom.UncheckedJDOMFactory;
import org.jdom.input.SAXBuilder;
import org.xml.sax.XMLReader;
import com.sun.org.apache.xerces.internal.parsers.XMLParser;
public class UncheckedFactorySample {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
builder.setFeature("http://xml.org/sax/features/validation", false);
builder.setFactory(new UncheckedJDOMFactory());
Document doc = builder.build("bad.xml");
System.out.println(doc.getRootElement().getName());
}
}
Use XPath in servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class PostServlet extends HttpServlet {
private SAXBuilder builder = new SAXBuilder();
private XPath nameXPath;
private XPath yearXPath;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (!"text/xml".equals(request.getContentType())) {
response.getWriter().println("Please post as text/xml.");
} else {
try {
Document doc = builder.build(request.getReader());
StringBuffer buff = new StringBuffer();
buff.append("You searched for name "" + nameXPath.valueOf(doc)
+ """);
String year = yearXPath.valueOf(doc);
if (!"notselected".equals(year)) {
buff.append(" and year "" + year + """);
}
buff.append(".");
response.getWriter().print(buff.toString());
} catch (JDOMException e) {
response.getWriter().print(
"Error getting search terms: " + e.getMessage());
}
}
}
public void init() throws ServletException {
try {
nameXPath = XPath.newInstance("/search/name/text()");
yearXPath = XPath.newInstance("/search/year/text()");
} catch (JDOMException e) {
throw new ServletException("Unable to create XPaths", e);
}
super.init();
}
}
XPath with JDOM
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class MainClass {
public static void main(String[] args) throws Exception {
Namespace NS_GUEST = Namespace.getNamespace("g", "uri:c:guest");
Namespace NS_SCHEDULE = Namespace.getNamespace("s", "uri:c:schedule");
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("tds_ns.xml"));
XPath xPath = XPath.newInstance("/s:schedule/s:show[@date=$date]/g:guest");
xPath.addNamespace(NS_SCHEDULE);
xPath.addNamespace(NS_GUEST);
String formattedDate = new SimpleDateFormat("MM.dd.yy").format(new Date(2006, 5, 14));
xPath.setVariable("date", formattedDate);
Element guest = (Element) xPath.selectSingleNode(document);
System.out.println(guest.getChildText("name", NS_GUEST));
}
}