2 Copyright (C) 2000-2003 SKYRIX Software AG
4 This file is part of OGo
6 OGo is free software; you can redistribute it and/or modify it under
7 the terms of the GNU Lesser General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 OGo is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
14 License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with OGo; see the file COPYING. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
23 #include "NSString+misc.h"
26 @implementation NSString(XMLEscaping)
28 - (NSString *)stringByEscapingXMLStringUsingCharacters {
29 register unsigned i, len, j;
30 register unichar *chars, *buf;
33 if ((len = [self length]) == 0) return @"";
35 chars = malloc((len + 3) * sizeof(unichar));
36 [self getCharacters:chars];
38 /* check for characters to escape ... */
39 for (i = 0, escapeCount = 0; i < len; i++) {
41 case '&': case '"': case '<': case '>':
50 if (escapeCount == 0 ) {
51 /* nothing to escape ... */
52 if (chars) free(chars);
53 return [[self copy] autorelease];
56 buf = malloc(((len + 3) * sizeof(unichar)) +
57 (escapeCount * 8 * sizeof(unichar)));
58 for (i = 0, j = 0; i < len; i++) {
60 /* escape special chars */
62 buf[j] = '&'; j++; buf[j] = 'a'; j++; buf[j] = 'm'; j++;
63 buf[j] = 'p'; j++; buf[j] = ';'; j++;
66 buf[j] = '&'; j++; buf[j] = 'q'; j++; buf[j] = 'u'; j++;
67 buf[j] = 'o'; j++; buf[j] = 't'; j++; buf[j] = ';'; j++;
70 buf[j] = '&'; j++; buf[j] = 'l'; j++; buf[j] = 't'; j++;
74 buf[j] = '&'; j++; buf[j] = 'g'; j++; buf[j] = 't'; j++;
79 /* escape big chars */
81 unsigned char nbuf[16];
84 sprintf(nbuf, "&#%i;", (int)chars[i]);
85 for (k = 0; nbuf[k] != '\0'; k++) {
91 /* nothing to escape */
99 self = [NSString stringWithCharacters:buf length:j];
101 if (chars) free(chars);
106 - (NSString *)stringByEscapingXMLString {
107 return [self stringByEscapingXMLStringUsingCharacters];
110 - (NSString *)stringByEscapingXMLAttributeValue {
111 return [self stringByEscapingHTMLAttributeValue];
117 if ([self length] == 0) return NO;
118 return [self characterAtIndex:0] == '{' ? YES : NO;
121 - (NSString *)xmlNamespaceURI {
124 r = [self rangeOfString:@"}" options:(NSLiteralSearch | NSBackwardsSearch)];
125 if (r.length == 0) return nil;
126 if ([self characterAtIndex:0] != '{') return nil;
128 r.length = (r.location - 1);
130 return [self substringWithRange:r];
133 - (NSString *)xmlLocalName {
136 r = [self rangeOfString:@"}" options:(NSLiteralSearch | NSBackwardsSearch)];
137 if (r.length == 0) return nil;
138 if ([self characterAtIndex:0] != '{') return nil;
140 return [self substringFromIndex:(r.location + r.length)];
143 @end /* NSString(XMLEscaping) */