1 21 22 package nu.xom.samples; 23 24 import java.io.IOException ; 25 import java.io.OutputStream ; 26 import java.io.UnsupportedEncodingException ; 27 28 import nu.xom.Builder; 29 import nu.xom.Document; 30 import nu.xom.Element; 31 import nu.xom.Node; 32 import nu.xom.ParentNode; 33 import nu.xom.ParsingException; 34 import nu.xom.Serializer; 35 36 37 48 public final class NonRecursiveSerializer extends Serializer { 49 50 51 public NonRecursiveSerializer(OutputStream out) { 52 super(out); 53 } 54 55 56 public NonRecursiveSerializer(OutputStream out, String encoding) 57 throws UnsupportedEncodingException { 58 super(out, encoding); 59 } 60 61 62 protected final void write(Element element) 63 throws IOException { 64 65 if (element.getChildCount() == 0) { 67 super.writeEmptyElementTag(element); 68 } 69 else { 70 Node current = element; 71 boolean end = false; 72 int index = -1; 73 while (true) { 74 if (!end && current.getChildCount() > 0) { 75 writeStartTag((Element) current); 76 current = current.getChild(0); 77 index = 0; 78 } 79 else { 80 if (end) { 81 writeEndTag((Element) current); 82 if (current == element) break; 83 } 84 else { 85 writeChild(current); 86 } 87 end = false; 88 ParentNode parent = current.getParent(); 89 if (parent.getChildCount() - 1 == index) { 90 current = parent; 91 if (current != element) { 92 parent = current.getParent(); 93 index = parent.indexOf(current); 94 } 95 end = true; 96 } 97 else { 98 index++; 99 current = parent.getChild(index); 100 } 101 } 102 } 103 } 104 105 } 106 107 108 public static void main(String [] args) { 109 110 if (args.length <= 0) { 111 System.out.println("Usage: java nu.xom.samples.PrettyPrinter URL"); 112 return; 113 } 114 115 try { 116 Builder parser = new Builder(); 117 Document doc = parser.build(args[0]); 118 Serializer serializer = new Serializer(System.out, "ISO-8859-1"); 119 serializer.setIndent(4); 120 serializer.setMaxLength(64); 121 serializer.setPreserveBaseURI(true); 122 serializer.write(doc); 123 serializer.flush(); 124 } 125 catch (ParsingException ex) { 126 System.out.println(args[0] + " is not well-formed."); 127 System.out.println(ex.getMessage()); 128 } 129 catch (IOException ex) { 130 System.out.println( 131 "Due to an IOException, the parser could not check " 132 + args[0] 133 ); 134 } 135 136 } 137 138 } 139 | Popular Tags |