Java Reference
In-Depth Information
...
</book>
<book isbn="...">
<title>Grails in Action</title>
<author>Glen Smith</author>
<author>Peter Ledbrook</author>
</book>
<book isbn="...">
<title>Making Java Groovy [ 11 ] </title>
<author>Ken Kousen</author>
</book>
</books>
11 I had to find some way to include my book in that august company, just to bask in the reflected glory.
Now assume that my task is to print the title of the second book. What could be easier?
Here's one Java solution, based on parsing the data into a document object model (DOM)
tree and finding the right element:
public class ProcessBooks {
public static void main(String[] args) {
DocumentBuilderFactory factory =
DocumentBuilderFactory. newInstance ();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse("src/jag/xml/books.xml");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (doc == null) return;
NodeList titles = doc.getElementsByTagName("title");
Element titleNode = (Element) titles.item(1);
String title = titleNode.getFirstChild().getNodeValue();
System.out.println("The second title is " + title);
}
}
Thisisactuallytheshortversionoftherequiredprogram.TomakeitanyshorterI'dhaveto
collapse the exception handling into catching just Exception , or add a throws clause
to the main method.
 
Search WWH ::




Custom Search