1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.xchain.framework.sax.util;
17
18 import org.xchain.framework.sax.HandlerWrapper;
19 import org.xml.sax.ErrorHandler;
20 import org.xml.sax.Attributes;
21 import org.xml.sax.helpers.AttributesImpl;
22 import org.xml.sax.SAXException;
23
24
25
26
27
28
29
30 public class XHtmlHandler
31 extends HandlerWrapper
32 {
33 public static String HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
34
35 protected NamespaceContext inputNamespaceContext = new NamespaceContext();
36
37 public void startElement( String namespaceUri, String localName, String qName, Attributes attributes )
38 throws SAXException
39 {
40 if( HTML_NAMESPACE.equals(namespaceUri) ) {
41 super.startElement("", localName, localName, filterAttributes(attributes));
42 }
43 else {
44 super.startElement(namespaceUri, localName, qName, attributes);
45 }
46 }
47
48 public void endElement( String namespaceUri, String localName, String qName )
49 throws SAXException
50 {
51 if( HTML_NAMESPACE.equals(namespaceUri) ) {
52 super.endElement("", localName, localName);
53 }
54 else {
55 super.endElement(namespaceUri, localName, qName);
56 }
57 }
58
59 public void startPrefixMapping( String prefix, String namespaceUri )
60 throws SAXException
61 {
62 inputNamespaceContext.startPrefixMapping(prefix, namespaceUri);
63
64
65 if( HTML_NAMESPACE.equals(namespaceUri) ) {
66
67 super.startPrefixMapping("", "");
68 }
69 else if( inputNamespaceContext.isPrefixMappingNeeded(prefix) ) {
70
71 super.startPrefixMapping(prefix, namespaceUri);
72 }
73
74 }
75
76 public void endPrefixMapping( String prefix )
77 throws SAXException
78 {
79 String namespaceUri = inputNamespaceContext.lookupUri( prefix );
80
81 if( HTML_NAMESPACE.equals(namespaceUri) ) {
82 super.endPrefixMapping("");
83 }
84 else if( inputNamespaceContext.isPrefixMappingNeeded(prefix) ) {
85 super.endPrefixMapping(prefix);
86 }
87
88 inputNamespaceContext.endPrefixMapping(prefix);
89 }
90
91 public Attributes filterAttributes( Attributes attributes )
92 {
93 if( attributes.getLength() == 0 ) {
94 return attributes;
95 }
96
97
98 AttributesImpl filteredAttributes = new AttributesImpl();
99 for( int i = 0; i < attributes.getLength(); i++ ) {
100 if( HTML_NAMESPACE.equals(attributes.getURI(i)) ) {
101 if( attributes.getIndex(attributes.getLocalName(i)) == -1 ) {
102 filteredAttributes.addAttribute("", attributes.getLocalName(i), attributes.getLocalName(i), attributes.getType(i), attributes.getValue(i));
103 }
104 }
105 else {
106 filteredAttributes.addAttribute(attributes.getURI(i), attributes.getLocalName(i), attributes.getQName(i), attributes.getType(i), attributes.getValue(i));
107 }
108 }
109
110 return filteredAttributes;
111 }
112 }