1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package net.sf.jdiskcatalog.io;
24
25 import org.w3c.dom.Document;
26 import org.w3c.dom.Element;
27 import org.w3c.dom.Node;
28 import org.xml.sax.Attributes;
29 import org.xml.sax.SAXException;
30 import org.xml.sax.helpers.DefaultHandler;
31
32 import com.sun.org.apache.xerces.internal.dom.DocumentImpl;
33
34 public class Sax2Dom extends DefaultHandler
35 {
36 private Document document = null;
37 private Node currentNode = null;
38 private StringBuilder characters = null;
39
40 @Override
41 public void startDocument() throws SAXException
42 {
43 document = new DocumentImpl();
44 currentNode = document;
45 }
46
47 @Override
48 public void characters(char[] ch, int start, int length) throws SAXException
49 {
50 characters.append(ch, start, length);
51 }
52
53 @Override
54 public void endElement(String uri, String localName, String qName) throws SAXException
55 {
56 if (characters.length() > 0)
57 {
58 Node n = document.createTextNode(characters.toString());
59 currentNode.appendChild(n);
60 }
61 currentNode = currentNode.getParentNode();
62 }
63
64 @Override
65 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
66 {
67 characters = new StringBuilder();
68 Element el = document.createElement(qName);
69 for (int i=0; i < attributes.getLength(); i++)
70 {
71 String attName = attributes.getQName(i);
72 String attValue = attributes.getValue(i);
73 el.setAttribute(attName, attValue);
74 }
75 currentNode.appendChild(el);
76 currentNode = el;
77 }
78
79 public Document getDocument()
80 {
81 return document;
82 }
83
84
85 }