2 Copyright (C) 2000-2005 SKYRIX Software AG
4 This file is part of SOPE.
6 SOPE 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 SOPE 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 SOPE; see the file COPYING. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 #include "NSString+misc.h"
25 @implementation NSString(XMLEscaping)
27 - (NSString *)stringByEscapingXMLStringUsingCharacters {
28 register unsigned i, len, j;
29 register unichar *chars, *buf;
32 if ((len = [self length]) == 0) return @"";
34 chars = malloc((len + 3) * sizeof(unichar));
35 [self getCharacters:chars];
37 /* check for characters to escape ... */
38 for (i = 0, escapeCount = 0; i < len; i++) {
40 case '&': case '"': case '<': case '>':
49 if (escapeCount == 0 ) {
50 /* nothing to escape ... */
51 if (chars) free(chars);
52 return [[self copy] autorelease];
55 buf = malloc(((len + 3) * sizeof(unichar)) +
56 (escapeCount * 8 * sizeof(unichar)));
57 for (i = 0, j = 0; i < len; i++) {
59 /* escape special chars */
61 buf[j] = '&'; j++; buf[j] = 'a'; j++; buf[j] = 'm'; j++;
62 buf[j] = 'p'; j++; buf[j] = ';'; j++;
65 buf[j] = '&'; j++; buf[j] = 'q'; j++; buf[j] = 'u'; j++;
66 buf[j] = 'o'; j++; buf[j] = 't'; j++; buf[j] = ';'; j++;
69 buf[j] = '&'; j++; buf[j] = 'l'; j++; buf[j] = 't'; j++;
73 buf[j] = '&'; j++; buf[j] = 'g'; j++; buf[j] = 't'; j++;
78 /* escape big chars */
80 unsigned char nbuf[16];
83 sprintf(nbuf, "&#%i;", (int)chars[i]);
84 for (k = 0; nbuf[k] != '\0'; k++) {
90 /* nothing to escape */
98 self = [NSString stringWithCharacters:buf length:j];
100 if (chars) free(chars);
105 - (NSString *)stringByEscapingXMLString {
106 return [self stringByEscapingXMLStringUsingCharacters];
109 - (NSString *)stringByEscapingXMLAttributeValue {
110 return [self stringByEscapingHTMLAttributeValue];
116 if ([self length] == 0) return NO;
117 return [self characterAtIndex:0] == '{' ? YES : NO;
120 - (NSString *)xmlNamespaceURI {
123 r = [self rangeOfString:@"}" options:(NSLiteralSearch | NSBackwardsSearch)];
124 if (r.length == 0) return nil;
125 if ([self characterAtIndex:0] != '{') return nil;
127 r.length = (r.location - 1);
129 return [self substringWithRange:r];
132 - (NSString *)xmlLocalName {
135 r = [self rangeOfString:@"}" options:(NSLiteralSearch | NSBackwardsSearch)];
136 if (r.length == 0) return nil;
137 if ([self characterAtIndex:0] != '{') return nil;
139 return [self substringFromIndex:(r.location + r.length)];
142 @end /* NSString(XMLEscaping) */