01: package org.htmlcleaner;
02:
03: import org.w3c.dom.*;
04:
05: import javax.xml.parsers.DocumentBuilderFactory;
06: import javax.xml.parsers.ParserConfigurationException;
07: import java.util.List;
08: import java.util.Iterator;
09: import java.util.Map;
10:
11: /**
12: * <p>DOM serializer - creates xml DOM.</p>
13: *
14: * Created by: Vladimir Nikic<br/>
15: * Date: April, 2007.
16: */
17: public class DomSerializer {
18:
19: public Document createDOM(TagNode rootNode)
20: throws ParserConfigurationException {
21: DocumentBuilderFactory factory = DocumentBuilderFactory
22: .newInstance();
23:
24: Document document = factory.newDocumentBuilder().newDocument();
25: Element rootElement = document
26: .createElement(rootNode.getName());
27: document.appendChild(rootElement);
28:
29: createSubnodes(document, rootElement, rootNode.getChildren());
30:
31: return document;
32: }
33:
34: private void createSubnodes(Document document, Element element,
35: List tagChildren) {
36: if (tagChildren != null) {
37: Iterator it = tagChildren.iterator();
38: while (it.hasNext()) {
39: Object item = it.next();
40: if (item instanceof CommentToken) {
41: CommentToken commentToken = (CommentToken) item;
42: Comment comment = document
43: .createComment(commentToken.getContent());
44: element.appendChild(comment);
45: } else if (item instanceof ContentToken) {
46: ContentToken contentToken = (ContentToken) item;
47: Text text = document.createTextNode(contentToken
48: .getContent());
49: element.appendChild(text);
50: } else if (item instanceof TagNode) {
51: TagNode subTagNode = (TagNode) item;
52: Element subelement = document
53: .createElement(subTagNode.getName());
54: Map attributes = subTagNode.getAttributes();
55: Iterator entryIterator = attributes.entrySet()
56: .iterator();
57: while (entryIterator.hasNext()) {
58: Map.Entry entry = (Map.Entry) entryIterator
59: .next();
60: String attrName = (String) entry.getKey();
61: String attrValue = (String) entry.getValue();
62: subelement.setAttribute(attrName, attrValue);
63: }
64:
65: // recursively create subnodes
66: createSubnodes(document, subelement, subTagNode
67: .getChildren());
68:
69: element.appendChild(subelement);
70: } else if (item instanceof List) {
71: List sublist = (List) item;
72: createSubnodes(document, element, sublist);
73: }
74: }
75: }
76: }
77:
78: }
|