log4j src – parse log4j.xml building DocumentBuilder

log4j uses DocumentBuilder to parse log4j.xml

here is example code which is same as log4j original source code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 
package main;
 
import java.io.*;
import java.net.*;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
public class DocumentBuilderEntry {
 
	public static void loop(Node node) {
	    // do something with the current node instead of System.out
	    System.out.println(node.getNodeName());
 
	    NodeList nodeList = node.getChildNodes();
	    for (int i = 0; i < nodeList.getLength(); i++) {
	        Node currentNode = nodeList.item(i);
	        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
	            //calls this method for all the children which is Element
	        	loop(currentNode);
	        }
	    }
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		URL url = DocumentBuilderEntry.class.getResource("log4j.xml");
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
		try {
			DocumentBuilder parser = factory.newDocumentBuilder();
			URLConnection uConn = url.openConnection();
 
			uConn.setUseCaches(false);
			InputStream stream = uConn.getInputStream();
			try {
			  InputSource src = new InputSource(stream);
			  src.setSystemId(url.toString());
			  Document doc = parser.parse(src);
			  loop(doc.getDocumentElement());
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
			  stream.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 
 
 
	}
 
}