import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; public class DomParser { public void createNode(Document doc)throws IOException { Node rootNode = doc.getDocumentElement(); Element element = doc.createElement("book"); element.setAttribute("category","Java"); Node nodeTitle = doc.createElement("title"); Text textTitle = doc.createTextNode("Java world"); nodeTitle.appendChild(textTitle); Node nodeAuthor = doc.createElement("author"); Text textAuthor = doc.createTextNode("Ahmed Hashim"); nodeAuthor.appendChild(textAuthor); element.appendChild(nodeTitle); element.appendChild(nodeAuthor); rootNode.appendChild(element); } public void parseNode(Node node)throws IOException { NodeList nodes = null; if(node.getNodeType() == Node.DOCUMENT_NODE) { System.out.println("/* Catalog contain books*/"); nodes = node.getChildNodes(); if(nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { parseNode(nodes.item(i)); } } } else if(node.getNodeType() == Node.ELEMENT_NODE) { NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { System.out.println("Category: "+attrs.item(i).getNodeValue()); } if(node.getNodeName().equals("title")) { System.out.print("Title:"); } else if(node.getNodeName().equals("author")) { System.out.print("Author:"); } nodes = node.getChildNodes(); if(nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { parseNode(nodes.item(i)); } } } else if(node.getNodeType() == Node.TEXT_NODE) { if(node.getNodeValue().length()>3) { System.out.println(node.getNodeValue()); } } } public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("books.xml"); DomParser dom = new DomParser(); dom.createNode(doc); dom.parseNode(doc); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }