01: /*
02: * Copyright (C) 2006 Joe Walnes.
03: * Copyright (C) 2006, 2007, 2008 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 04. June 2006 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.io.copy;
13:
14: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
15: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
16:
17: /**
18: * Tool for copying the contents of one HierarichalStreamReader to a HierarichalStreamWriter.
19: * <p/>
20: * This is useful for transforming the output of one format to another (e.g. binary to XML)
21: * without needing to know details about the classes and avoiding the overhead of serialization.
22: *
23: * <h3>Example</h3>
24: * <pre>
25: * HierarchicalStreamReader reader = new BinaryStreamReader(someBinaryInput);
26: * HierarchicalStreamWriter writer = new PrettyPrintWriter(someXmlOutput);
27: * HierarchicalStreamCopier copier = new HierarchicalStreamCopier();
28: * copier.copy(reader, writer);
29: * </pre>
30: *
31: * @author Joe Walnes
32: * @since 1.2
33: */
34: public class HierarchicalStreamCopier {
35: public void copy(HierarchicalStreamReader source,
36: HierarchicalStreamWriter destination) {
37: destination.startNode(source.getNodeName());
38: int attributeCount = source.getAttributeCount();
39: for (int i = 0; i < attributeCount; i++) {
40: destination.addAttribute(source.getAttributeName(i), source
41: .getAttribute(i));
42: }
43: String value = source.getValue();
44: if (value != null && value.length() > 0) {
45: destination.setValue(value);
46: }
47: while (source.hasMoreChildren()) {
48: source.moveDown();
49: copy(source, destination);
50: source.moveUp();
51: }
52: destination.endNode();
53: }
54: }
|