Reputation: 16845
I need to manage xml with java. Only DOM is enough... I need something very simple or better I would really avoid to install new libraries...
what is the package to use in Java 6 ??
I looked in doc but nothing clear is provided, just a reference to xml in org but nothing good is provided... or I didn't find it :(
Thank you
Upvotes: 2
Views: 1510
Reputation: 11
Use JAXB and parse XMl to bind to a DataObject. handling a dataObject is easy. JAXB comes bundled with java 6 by default.
E.g.
JAXBContext jc = JAXBContext.newInstance("test.schema");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Note - Good option if your XML format is fixed.
Upvotes: 0
Reputation: 8979
This is an example. A complete tutorial can be found here
public class ChessboardDOMPrinter {
private DocumentBuilder builder;
public void print(String fileName, PrintStream out)
throws SAXException, IOException {
Document document = builder.parse(fileName);
NodeList nodes_i
= document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodes_i.getLength(); i++) {
Node node_i = nodes_i.item(i);
if (node_i.getNodeType() == Node.ELEMENT_NODE
&& ((Element) node_i).getTagName()
.equals("CHESSBOARD")) {
Element chessboard = (Element) node_i;
NodeList nodes_j = chessboard.getChildNodes();
for (int j = 0; j < nodes_j.getLength(); j++) {
Node node_j = nodes_j.item(j);
if (node_j.getNodeType() == Node.ELEMENT_NODE) {
Element pieces = (Element) node_j;
NodeList nodes_k = pieces.getChildNodes();
for (int k = 0; k < nodes_k.getLength(); k++) {
Node node_k = nodes_k.item(k);
if (node_k.getNodeType() == Node.ELEMENT_NODE) {
Element piece = (Element) node_k;
Element position
= (Element) piece.getChildNodes().item(0);
out.println((pieces.getTagName()
.equals("WHITEPIECES")
? "White " : "Black ")
+ piece.getTagName().toLowerCase()
+ ": "
+ position.getAttribute("COLUMN")
+ position.getAttribute("ROW"));
}
}
}
}
}
}
return;
}
}
Upvotes: 1
Reputation: 29139
XML DOM parser is included in Java 6. Here is a snippet for how to use it:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
....
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = docbuilder.parse( new InputSource( reader ) )
Upvotes: 3
Reputation: 38777
The DOM API is in org.w3c.dom
. To get started you'll need to use a javax.xml.parsers.DocumentBuilder
, which can be got from javax.xml.parsers.DocumentBuilderFactory
.
All this is shipped with Java 6 by default.
Upvotes: 2