XML with Java 1.5

This is how you can validate an xml file with a xsd schema using the Java built-in libraries. Look for the sample code at the bottom of the page. After some painful hours, I found out that it doesn’t work with DTDs (although it says it does…). If you have a DTD, then refer to earlier post and look for a conversion tool (DTD to XSD).

Similarly, this is how you would create an xml document with the built-in java library:

try {
Document doc =
DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();

Element root = doc.createElement(”book”);
Element child = doc.createElement(”author”);
child.setAttribute(”id”, “Eric The Great”);
root.appendChild(child);
doc.appendChild(root);

} catch (ParserConfigurationException e) { … }

The previous code should generate this xml document: (please note that I changed pointy brackets to square ones on purpose)

[book]
[author id=”Eric The Great”/]
[/book]

For XPath to find 1 node:

XPath xpath = XPathFactory
.newInstance().newXPath();

String expression = “book/author”;

Node node = (Node)
xpath.evaluate(expression,
document, XPathConstants.NODE);

String value =
node.getAttributes()
.getNamedItem(ATTRIBUTE_NAME)
.getNodeValue();

For XPath to find a list of nodes:

NodeList nodeList =
(NodeList) xpath.evaluate(expression,
document, XPathConstants.NODESET);

Note: Be careful which library you import because many classnames are very common, like Document, Node, Element, etc. The classes shown here are either from org.w3c.dom or from javax.xml.

For more complicated things……….. LOOK IT UP YOURSELF!!

Explore posts in the same categories: Uncategorized, Java, XML

3 Comments on “XML with Java 1.5”

  1. Ahmed Says:

    Excelent :grin:

    Thanks Eric :razz:

  2. Willem Says:

    Thanks a lot!!!

    After spending hours importing classes from every conceivable source I finally have a working sample thanks to your blog post

  3. Eric Says:

    Wow… It’s an honor to hear that. I never really thought that my post would actually help others… Thanks for posting this comment. You really made me feel I am useful… for once! LOL :)

Comment:

Logged in as . Logout »