001: package com.jeta.forms.store.xml;
002:
003: import org.xml.sax.Attributes;
004:
005: import com.jeta.forms.store.jml.dom.DefaultAttributes;
006: import com.jeta.forms.store.jml.dom.JMLAttributes;
007:
008: public class XMLUtils {
009:
010: /**
011: * Escape the "special" characters as required for inclusion in XML elements
012: * Replaces all incidences of & with & < with < > with > " with " ' with
013: * '
014: *
015: * @param s
016: * The string to scan
017: * @return String
018: */
019: public static String escape(String s) {
020: char[] array = s.toCharArray();
021: StringBuffer sb = new StringBuffer();
022: for (int i = 0; i < array.length; i++) {
023: switch (array[i]) {
024: case '&':
025: sb.append("&");
026: break;
027: case '<':
028: sb.append("<");
029: break;
030: case '>':
031: sb.append(">");
032: break;
033: case '"':
034: sb.append(""");
035: break;
036: case '\'':
037: sb.append("'");
038: break;
039: default:
040: sb.append(array[i]);
041: }
042: }
043: return sb.toString();
044: }
045:
046: public static String unescape(String str) {
047: // < <
048: // > >
049: // & &
050: // " "
051: // ' '
052:
053: if (str == null)
054: return null;
055:
056: StringBuffer sbuff = new StringBuffer();
057: for (int index = 0; index < str.length(); index++) {
058: char c = str.charAt(index);
059:
060: if (c == '&') {
061: if (index + 3 < str.length()) {
062: char c1 = str.charAt(index + 1);
063: char c2 = str.charAt(index + 2);
064: char c3 = str.charAt(index + 3);
065:
066: if (c1 == 'l' && c2 == 't' && c3 == ';') {
067: sbuff.append('<');
068: index += 3;
069: continue;
070: } else if (c1 == 'g' && c2 == 't' && c3 == ';') {
071: sbuff.append('>');
072: index += 3;
073: continue;
074: } else {
075: if (index + 4 < str.length()) {
076: char c4 = str.charAt(index + 4);
077: if (c1 == 'a' && c2 == 'm' && c3 == 'p'
078: && c4 == ';') {
079: sbuff.append('&');
080: index += 4;
081: continue;
082: } else {
083: if (index + 5 < str.length()) {
084: char c5 = str.charAt(index + 5);
085: if (c1 == 'q' && c2 == 'u'
086: && c3 == 'o' && c4 == 't'
087: && c5 == ';') {
088: sbuff.append('\"');
089: index += 5;
090: continue;
091: } else if (c1 == 'a' && c2 == 'p'
092: && c3 == 'o' && c4 == 's'
093: && c5 == ';') {
094: sbuff.append('\'');
095: index += 5;
096: continue;
097: }
098: }
099: }
100: }
101: }
102: }
103: }
104: sbuff.append(c);
105: }
106: return sbuff.toString();
107: }
108:
109: /**
110: * Converts a SAX Attributes to a JML Attributes
111: *
112: * @param attributes
113: * @return
114: */
115: public static JMLAttributes toJMLAttributes(Attributes attributes) {
116: DefaultAttributes da = new DefaultAttributes();
117: for (int index = 0; index < attributes.getLength(); index++) {
118: String qname = attributes.getQName(index);
119: da.setAttribute(qname, attributes.getValue(qname));
120: }
121: return da;
122: }
123:
124: }
|