1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.xml.stream;
18
19 import java.util.Iterator;
20 import javax.xml.namespace.QName;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.stream.XMLStreamWriter;
23
24 import org.springframework.util.StringUtils;
25 import org.springframework.xml.namespace.QNameUtils;
26 import org.springframework.xml.namespace.SimpleNamespaceContext;
27 import org.xml.sax.Attributes;
28 import org.xml.sax.Locator;
29
30
31
32
33
34
35
36
37 public class StaxStreamContentHandler extends AbstractStaxContentHandler {
38
39 private final XMLStreamWriter streamWriter;
40
41
42
43
44
45
46
47 public StaxStreamContentHandler(XMLStreamWriter streamWriter) {
48 this.streamWriter = streamWriter;
49 }
50
51 public void setDocumentLocator(Locator locator) {
52 }
53
54 protected void charactersInternal(char[] ch, int start, int length) throws XMLStreamException {
55 streamWriter.writeCharacters(ch, start, length);
56 }
57
58 protected void endDocumentInternal() throws XMLStreamException {
59 streamWriter.writeEndDocument();
60 }
61
62 protected void endElementInternal(QName name, SimpleNamespaceContext namespaceContext) throws XMLStreamException {
63 streamWriter.writeEndElement();
64 }
65
66 protected void ignorableWhitespaceInternal(char[] ch, int start, int length) throws XMLStreamException {
67 streamWriter.writeCharacters(ch, start, length);
68 }
69
70 protected void processingInstructionInternal(String target, String data) throws XMLStreamException {
71 streamWriter.writeProcessingInstruction(target, data);
72 }
73
74 protected void skippedEntityInternal(String name) {
75 }
76
77 protected void startDocumentInternal() throws XMLStreamException {
78 streamWriter.writeStartDocument();
79 }
80
81 protected void startElementInternal(QName name, Attributes attributes, SimpleNamespaceContext namespaceContext)
82 throws XMLStreamException {
83 streamWriter.writeStartElement(QNameUtils.getPrefix(name), name.getLocalPart(), name.getNamespaceURI());
84 String defaultNamespaceUri = namespaceContext.getNamespaceURI("");
85 if (StringUtils.hasLength(defaultNamespaceUri)) {
86 streamWriter.writeNamespace("", defaultNamespaceUri);
87 streamWriter.setDefaultNamespace(defaultNamespaceUri);
88 }
89 for (Iterator iterator = namespaceContext.getBoundPrefixes(); iterator.hasNext();) {
90 String prefix = (String) iterator.next();
91 streamWriter.writeNamespace(prefix, namespaceContext.getNamespaceURI(prefix));
92 streamWriter.setPrefix(prefix, namespaceContext.getNamespaceURI(prefix));
93 }
94 for (int i = 0; i < attributes.getLength(); i++) {
95 QName attrName = QNameUtils.toQName(attributes.getURI(i), attributes.getQName(i));
96 String attrPrefix = QNameUtils.getPrefix(attrName);
97 if (!("xmlns".equals(attrName.getLocalPart()) || "xmlns".equals(attrPrefix))) {
98 streamWriter.writeAttribute(attrPrefix, attrName.getNamespaceURI(), attrName.getLocalPart(),
99 attributes.getValue(i));
100 }
101 }
102 }
103 }