KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > nu > xom > samples > SourceCodeSerializer


1 /* Copyright 2004 Elliotte Rusty Harold
2    
3    This library is free software; you can redistribute it and/or modify
4    it under the terms of version 2.1 of the GNU Lesser General Public
5    License as published by the Free Software Foundation.
6    
7    This library is distributed in the hope that it will be useful,
8    but WITHOUT ANY WARRANTY; without even the implied warranty of
9    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10    GNU Lesser General Public License for more details.
11    
12    You should have received a copy of the GNU Lesser General Public
13    License along with this library; if not, write to the
14    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
15    Boston, MA 02111-1307 USA
16    
17    You can contact Elliotte Rusty Harold by sending e-mail to
18    elharo@metalab.unc.edu. Please include the word "XOM" in the
19    subject line. The XOM home page is located at http://www.xom.nu/
20 */

21
22 package nu.xom.samples;
23
24 import java.io.IOException JavaDoc;
25 import java.io.OutputStream JavaDoc;
26 import java.io.UnsupportedEncodingException JavaDoc;
27 import java.util.Stack JavaDoc;
28
29 import nu.xom.Attribute;
30 import nu.xom.Builder;
31 import nu.xom.Comment;
32 import nu.xom.DocType;
33 import nu.xom.Document;
34 import nu.xom.Element;
35 import nu.xom.ParsingException;
36 import nu.xom.ProcessingInstruction;
37 import nu.xom.Serializer;
38 import nu.xom.Text;
39
40 /**
41  * <p>
42  * This class converts an XML document into XOM source code that
43  * creates the same XML document. It's often useful for
44  * building self-contained unit tests.
45  * </p>
46  *
47  * @author Elliotte Rusty Harold
48  * @version 1.0
49  *
50  */

51 public class SourceCodeSerializer extends Serializer {
52
53     public SourceCodeSerializer(OutputStream JavaDoc out) {
54         super(out);
55     }
56
57     public SourceCodeSerializer(OutputStream JavaDoc out, String JavaDoc encoding)
58       throws UnsupportedEncodingException JavaDoc {
59         super(out, encoding);
60     }
61     
62     
63     private Stack JavaDoc parents = new Stack JavaDoc();
64
65     
66     public void write(Document doc) throws IOException JavaDoc {
67         parents.push("doc");
68         Element root = doc.getRootElement();
69                 
70         write(root);
71         
72         // prolog
73
for (int i = 0; i < doc.indexOf(root); i++) {
74             writeChild(doc.getChild(i));
75         }
76         
77         //epilog
78
for (int i = doc.indexOf(root) + 1; i < doc.getChildCount(); i++) {
79             writeChild(doc.getChild(i));
80         }
81         
82         flush();
83         
84     }
85     
86     private int count = 1;
87     
88     protected void writeStartTag(Element element)
89       throws IOException JavaDoc {
90         
91         String JavaDoc name = "e" + count;
92         writeRaw("Element " + name + " = new Element(\""
93            + element.getQualifiedName() + "\", \"" + element.getNamespaceURI() + "\");");
94         breakLine();
95         if (count == 1) {
96             writeRaw("Document doc = new Document(e1);");
97         }
98         else {
99             writeRaw(parents.peek() + ".appendChild(" + name + ");");
100         }
101         breakLine();
102         parents.push(name);
103         writeAttributes(element);
104         writeNamespaceDeclarations(element);
105         count++;
106         
107     }
108
109     protected void writeEndTag(Element element) throws IOException JavaDoc {
110         parents.pop();
111     }
112
113
114     protected void writeEmptyElementTag(Element element) throws IOException JavaDoc {
115         writeStartTag(element);
116         writeEndTag(element);
117     }
118
119     protected void writeAttributes(Element element)
120       throws IOException JavaDoc {
121         
122         for (int i = 0; i < element.getAttributeCount(); i++) {
123             Attribute attribute = element.getAttribute(i);
124             write(attribute);
125         }
126         
127     }
128     
129
130     protected void write(Attribute attribute) throws IOException JavaDoc {
131         
132         String JavaDoc parent = (String JavaDoc) parents.peek();
133         writeRaw(parent + ".addAttribute(new Attribute(\"" + attribute.getQualifiedName() + "\", "
134           + "\"" + attribute.getNamespaceURI() + "\", \""
135           + escapeText(attribute.getValue()) + "\"));");
136         breakLine();
137         
138     }
139     
140     private static String JavaDoc escapeText(String JavaDoc s) {
141         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(s.length());
142         for (int i = 0; i < s.length(); i++) {
143             char c = s.charAt(i);
144             switch (c) {
145                 case '\n':
146                     sb.append("\\n");
147                     break;
148                 case '\r':
149                     sb.append("\\r");
150                     break;
151                 case '"':
152                     sb.append("\\\"");
153                     break;
154                 case '\t':
155                     sb.append("\\t");
156                     break;
157                 default:
158                     sb.append(c);
159             }
160         }
161         return sb.toString();
162     }
163
164
165     protected void writeNamespaceDeclarations(Element element)
166       throws IOException JavaDoc {
167         // We need to write only the additional namespace declarations
168
prefix: for (int i = 0; i < element.getNamespaceDeclarationCount(); i++) {
169             String JavaDoc prefix = element.getNamespacePrefix(i);
170             if (prefix.equals(element.getNamespacePrefix())) continue;
171             for (int a = 0; a < element.getAttributeCount(); a++) {
172                 if (prefix.equals(element.getAttribute(a).getNamespacePrefix())) {
173                     continue prefix;
174                 }
175             }
176             String JavaDoc parent = (String JavaDoc) parents.peek();
177             writeRaw(parent + ".addNamespaceDeclaration(\"" +
178               prefix + "\", \"" + element.getNamespaceURI(prefix) + "\");");
179             breakLine();
180         }
181
182     }
183
184
185     protected void write(ProcessingInstruction instruction)
186       throws IOException JavaDoc {
187         String JavaDoc parent = (String JavaDoc) parents.peek();
188         if (parent.equals("doc")) {
189             Document doc = instruction.getDocument();
190             int root = doc.indexOf(instruction);
191             writeRaw(parent + ".insertChild(new ProcessingInstruction(\"" + instruction.getTarget()
192                 + "\", \"" + escapeText(instruction.getValue()) + "\"), " + root + ");");
193         }
194         else {
195             writeRaw(parent
196                 + ".appendChild(new ProcessingInstruction(\""
197                 + instruction.getTarget()
198                 + "\", \"" + escapeText(instruction.getValue())
199                 + "\"));");
200         }
201         breakLine();
202     }
203
204
205     protected void write(DocType doctype) throws IOException JavaDoc {
206         writeRaw("DocType doctype = new DocType(\""
207                 + doctype.getRootElementName() + "\", \""
208                 + doctype.getPublicID() + "\", \""
209                 + doctype.getSystemID() +
210                         "\");");
211         breakLine();
212         Document doc = doctype.getDocument();
213         int root = doc.indexOf(doc.getRootElement());
214         writeRaw("doc.insertChild(doctype, " + root + ");");
215         breakLine();
216
217     }
218     
219     
220     protected void write(Comment comment) throws IOException JavaDoc {
221         String JavaDoc parent = (String JavaDoc) parents.peek();
222         if (parent.equals("doc")) {
223             Document doc = comment.getDocument();
224             int root = doc.indexOf(comment);
225             writeRaw(parent + ".insertChild(new Comment(\""
226               + escapeText(comment.getValue()) + "\"), "
227               + root + ");");
228         }
229         else {
230             writeRaw(parent + ".appendChild(new Comment(\""
231               + escapeText(comment.getValue()) + "\");");
232         }
233         breakLine();
234     }
235     
236     
237     protected void write(Text text) throws IOException JavaDoc {
238         String JavaDoc parent = (String JavaDoc) parents.peek();
239         writeRaw(parent + ".appendChild(new Text(\"" + escapeText(text.getValue()) + "\"));");
240         breakLine();
241     }
242     
243     
244     public static void main(String JavaDoc[] args) {
245   
246         if (args.length <= 0) {
247           System.out.println("Usage: java nu.xom.samples.SourceCodeSerializer URL");
248           return;
249         }
250         
251         try {
252           Builder parser = new Builder();
253           Document doc = parser.build(args[0]);
254           Serializer serializer = new SourceCodeSerializer(System.out, "ISO-8859-1");
255           serializer.write(doc);
256           serializer.flush();
257         }
258         catch (ParsingException ex) {
259           System.out.println(args[0] + " is not well-formed.");
260           System.out.println(ex.getMessage());
261         }
262         catch (IOException JavaDoc ex) {
263           System.out.println(
264            "Due to an IOException, the parser could not read "
265            + args[0]
266           );
267         }
268   
269     }
270
271 }
272
Popular Tags