View Javadoc

1   package org.ximtec.igesture.util;
2   
3   import java.io.File;
4   import java.io.IOException;
5   import java.util.ArrayList;
6   import java.util.Iterator;
7   
8   import javax.xml.parsers.DocumentBuilder;
9   import javax.xml.parsers.DocumentBuilderFactory;
10  import javax.xml.parsers.ParserConfigurationException;
11  
12  import org.w3c.dom.Document;
13  import org.w3c.dom.Element;
14  import org.w3c.dom.Node;
15  import org.w3c.dom.NodeList;
16  import org.xml.sax.SAXException;
17  
18  /**
19   * This class helps with parsing of configuration files.
20   * @author Bjorn Puype, bpuype@gmail.com
21   *
22   */
23  public abstract class XMLParser {
24  	
25  	/**
26  	 * Parse an XML file.
27  	 * @param fileName	The path of the file to parse.
28  	 * @param nodeName	The name of the nodes under the root node (should all be same type).
29  	 * @param textNodes	The names of the sub nodes of a node of type nodeName. These nodes should all be text nodes.
30  	 * @throws ParserConfigurationException
31  	 * @throws SAXException
32  	 * @throws IOException
33  	 */
34  	public void parse(String fileName, String nodeName, ArrayList<String> textNodes) throws ParserConfigurationException, SAXException, IOException
35  	{
36  		//location of the XML file
37  		File file = new File(fileName);
38  		//create a XML parser
39  		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
40  		DocumentBuilder db;
41  		db = dbf.newDocumentBuilder();
42  		//parse the XML file and create a DOM tree
43  		Document doc = db.parse(file);
44  		
45  		doc.getDocumentElement().normalize();
46  		//get all the nodeName elements
47  		NodeList nodeList = doc.getElementsByTagName(nodeName);
48  
49  		//for all nodeName elements, get all the subelements and put them in a arraylist
50  		//then execute the necessary operations on the parsed data
51  		for (int i = 0; i < nodeList.getLength(); i++) 
52  		{
53  		    Node node = nodeList.item(i);
54  		    
55  		    if (node.getNodeType() == Node.ELEMENT_NODE) 
56  		    {
57  		    	ArrayList<NodeList> nodeLists = new ArrayList<NodeList>();
58  		    	for(Iterator<String> iter = textNodes.iterator(); iter.hasNext(); )
59  		    	{
60  		    		NodeList nl = ((Element)node).getElementsByTagName(iter.next());
61  		    		nodeLists.add(((Element) nl.item(0)).getChildNodes());
62  		    	}
63  
64  			    execute(nodeLists);
65  		    }	    
66  		}
67  	}
68  
69  	/**
70  	 * This method is called for every node of type nodeName. This method has to be implemented to specify what to do with the
71  	 * parsed text nodes.
72  	 * @param nodeLists	A list with the parsed text nodes.
73  	 */
74  	public abstract void execute(ArrayList<NodeList> nodeLists);
75  	
76  }