View Javadoc

1   /*
2    * JDiskCatalog
3    *
4    * Copyright 2007 Przemek Więch
5    *
6    * This file is part of JDiskCatalog.
7    *
8    * JDiskCatalog is free software; you can redistribute it and/or modify
9    * it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation; either version 2 of the License, or
11   * (at your option) any later version.
12   *
13   * This program is distributed in the hope that it will be useful,
14   * but WITHOUT ANY WARRANTY; without even the implied warranty of
15   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   * GNU General Public License for more details.
17  
18   * You should have received a copy of the GNU General Public License
19   * along with this program; if not, write to the Free Software
20   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
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  }