1 36 37 package jnlp.sample.servlet; 38 39 import java.io.PrintWriter ; 40 import java.io.StringWriter ; 41 42 44 public class XMLNode { 45 private boolean _isElement; private String _name; 47 private XMLAttribute _attr; 48 private XMLNode _parent; private XMLNode _nested; private XMLNode _next; 52 53 public XMLNode(String name) { 54 this(name, null, null, null); 55 _isElement = false; 56 } 57 58 59 public XMLNode(String name, XMLAttribute attr) { 60 this(name, attr, null, null); 61 } 62 63 64 public XMLNode(String name, XMLAttribute attr, XMLNode nested, XMLNode next) { 65 _isElement = true; 66 _name = name; 67 _attr = attr; 68 _nested = nested; 69 _next = next; 70 _parent = null; 71 } 72 73 public String getName() { return _name; } 74 public XMLAttribute getAttributes() { return _attr; } 75 public XMLNode getNested() { return _nested; } 76 public XMLNode getNext() { return _next; } 77 public boolean isElement() { return _isElement; } 78 79 public void setParent(XMLNode parent) { _parent = parent; } 80 public XMLNode getParent() { return _parent; } 81 82 public void setNext(XMLNode next) { _next = next; } 83 public void setNested(XMLNode nested) { _nested = nested; } 84 85 public boolean equals(Object o) { 86 if (o == null || !(o instanceof XMLNode)) return false; 87 XMLNode other = (XMLNode)o; 88 boolean result = 89 match(_name, other._name) && 90 match(_attr, other._attr) && 91 match(_nested, other._nested) && 92 match(_next, other._next); 93 return result; 94 } 95 96 public String getAttribute(String name) { 97 XMLAttribute cur = _attr; 98 while(cur != null) { 99 if (name.equals(cur.getName())) return cur.getValue(); 100 cur = cur.getNext(); 101 } 102 return ""; 103 } 104 105 private static boolean match(Object o1, Object o2) { 106 if (o1 == null) return (o2 == null); 107 return o1.equals(o2); 108 } 109 110 public void printToStream(PrintWriter out) { 111 printToStream(out, 0); 112 } 113 114 public void printToStream(PrintWriter out, int n) { 115 if (!isElement()) { 116 out.print(_name); 117 } else { 118 if (_nested == null) { 119 String attrString = (_attr == null) ? "" : (" " + _attr.toString()); 120 lineln(out, n, "<" + _name + attrString + "/>"); 121 } else { 122 String attrString = (_attr == null) ? "" : (" " + _attr.toString()); 123 lineln(out, n, "<" + _name + attrString + ">"); 124 _nested.printToStream(out, n + 1); 125 if (_nested.isElement()) { 126 lineln(out, n, "</" + _name + ">"); 127 } else { 128 out.print("</" + _name + ">"); 129 } 130 } 131 } 132 if (_next != null) { 133 _next.printToStream(out, n); 134 } 135 } 136 137 private static void lineln(PrintWriter out, int indent, String s) { 138 out.println(""); 139 for(int i = 0; i < indent; i++) { 140 out.print(" "); 141 } 142 out.print(s); 143 } 144 145 public String toString() { 146 StringWriter sw = new StringWriter (1000); 147 PrintWriter pw = new PrintWriter (sw); 148 printToStream(pw); 149 pw.close(); 150 return sw.toString(); 151 } 152 } 153 154 155 | Popular Tags |