2 * $Id: ElementWriter.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $
3 * Copyright Narushima Hironori. All rights reserved.
5 package net.sourceforge.phpeclipse.wizards.html;
7 import java.io.IOException;
8 import java.io.OutputStream;
9 import java.io.OutputStreamWriter;
10 import java.util.HashMap;
12 import org.w3c.dom.Element;
13 import org.w3c.dom.NamedNodeMap;
14 import org.w3c.dom.Node;
15 import org.w3c.dom.NodeList;
16 import org.w3c.dom.Text;
19 * ElementWriter provides destribute xml code.
21 public class ElementWriter {
23 final public static int
28 HashMap expandOptions = new HashMap();
29 int defaultExpandOption;
32 public ElementWriter() {
36 public ElementWriter(int defaultExpandOption, String indent) {
37 this.defaultExpandOption = defaultExpandOption;
41 public void setExpandOption(String elementName, int value){
42 expandOptions.put(elementName, new Integer(value));
45 public int getExpandOption(String elementName){
46 if( expandOptions.containsKey(elementName)){
47 return ((Integer)expandOptions.get(elementName)).intValue();
49 return defaultExpandOption;
52 boolean isBeginChangeLine(String elementName){
53 return (getExpandOption(elementName) & BEGIN_CHANGELINE) != 0;
56 boolean isEndChangeLine(String elementName){
57 return (getExpandOption(elementName) & END_CHANGELINE) != 0;
60 public String expandTag(Element element){
61 StringBuffer buff = new StringBuffer();
62 expandTag(element, 0, buff);
63 return buff.toString();
66 public void writeTag(Element element, OutputStream out) throws IOException {
67 OutputStreamWriter writer = new OutputStreamWriter(out);
69 writer.write("<?xml version=\"1.0\"?>\n\n");
70 writer.write(new ElementWriter().expandTag(element));
78 void expandTag(Element element, int level, StringBuffer buff){
79 expandIndent(level, buff);
81 String elementName = element.getNodeName();
82 buff.append('<' + elementName );
83 NamedNodeMap attrs = element.getAttributes();
84 for(int i=0; i<attrs.getLength(); i++){
85 Node n = attrs.item(i);
86 String v = n.getNodeValue();
88 buff.append(' ' + n.getNodeName() + "=\"" + HTMLUtilities.escape(v) + "\"");
92 boolean emptyElem = element.getChildNodes().getLength() == 0;
98 NodeList childElements = element.getChildNodes();
99 if(isBeginChangeLine(elementName)){
102 for(int i=0; i<childElements.getLength(); i++){
103 Node node = childElements.item(i);
104 if( node instanceof Element){
105 expandTag( (Element)node, level+1, buff);
106 }else if (node instanceof Text){
107 String text = ((Text)node).getNodeValue();
108 if(trim && (text = text.trim()).length() == 0){
114 expandIndent(level, buff);
115 buff.append("</" + elementName + '>');
117 // already inserted change line.
118 if( isEndChangeLine(elementName) ){
123 void expandIndent(int level, StringBuffer buff){
125 for(int i=0; i<level; i++){
131 public int getDefaultExpandOption() {
132 return defaultExpandOption;
135 public void setDefaultExpandOption(int i) {
136 defaultExpandOption = i;