001: // XMLWriter.java
002: // $Id: XMLWriter.java,v 1.10 2007/04/04 12:29:42 ylafon Exp $
003: // (c) COPYRIGHT MIT, INRIA and Keio, 1999.
004: // Please first read the full copyright statement in file COPYRIGHT.html
005: package org.w3c.tools.resources.serialization.xml;
006:
007: import java.io.Writer;
008: import java.io.Reader;
009: import java.io.IOException;
010:
011: import org.w3c.tools.resources.Resource;
012: import org.w3c.tools.resources.ResourceFrame;
013: import org.w3c.tools.resources.Attribute;
014: import org.w3c.tools.resources.SimpleAttribute;
015: import org.w3c.tools.resources.ArrayAttribute;
016: import org.w3c.tools.resources.FrameArrayAttribute;
017:
018: /**
019: * @version $Revision: 1.10 $
020: * @author Benoît Mahé (bmahe@w3.org)
021: */
022: public class XMLWriter implements JigXML {
023:
024: protected Writer writer = null;
025: protected int level = 0;
026:
027: protected static String header = "<?xml version='1.0' encoding='UTF-8'?>\n<"
028: + JXML_TAG
029: + " version=\""
030: + version
031: + "\" xmlns=\""
032: + ns
033: + "\">\n";
034:
035: protected static char[] whitebuf = { ' ', ' ', ' ', ' ', ' ', ' ',
036: ' ', ' ' };
037:
038: protected void indent() throws IOException {
039: if (level > 0) {
040: int i = level;
041: while (i > 8) {
042: writer.write(whitebuf);
043: i = i - 8;
044: }
045: writer.write(whitebuf, 0, i);
046: }
047: }
048:
049: protected void startDocument() throws IOException {
050: // writer.write("<?xml version='1.0' encoding='UTF-8'?>\n<"
051: // +JXML_TAG+" version=\""+version+"\" xmlns=\""+
052: // ns+"\">\n");
053: writer.write(header);
054: }
055:
056: protected void closeDocument() throws IOException {
057: writer.write("</");
058: writer.write(JXML_TAG);
059: writer.write(">\n");
060: writer.close();
061: }
062:
063: protected void closeResource() throws IOException {
064: writer.write("</");
065: writer.write(RESOURCE_TAG);
066: writer.write(">\n");
067: }
068:
069: public XMLWriter(Writer writer) {
070: this .writer = writer;
071: }
072:
073: /**
074: * & => & < => <
075: */
076: public static String encode(String string) {
077: int len = string.length();
078: StringBuffer buffer = new StringBuffer(len + 16);
079: char c;
080: String s = null;
081:
082: synchronized (buffer) {
083: for (int i = 0; i < len; i++) {
084: switch (c = string.charAt(i)) {
085: case '&':
086: buffer.append("&");
087: break;
088: case '<':
089: buffer.append("<");
090: break;
091: case '>':
092: buffer.append(">");
093: break;
094: case '"':
095: buffer.append(""");
096: break;
097: default:
098: buffer.append(c);
099: }
100: }
101: s = buffer.toString();
102: }
103: return s;
104: }
105:
106: }
|