2

I am creating an application for iOS which needs to create an XML document. I do this via KissXML. Part of the XML looks like

<ISIN><![CDATA[12345678]]></ISIN>

I cannot find any option in KissXML to create the CDATA part. Simply adding a string with the CDATA stuff as text will result in escaping the special characters like < and >. Can anyone give me a hint in how to write CDATA with KissXML?

moq
  • 65
  • 6

2 Answers2

1

Even though the solution by @moq is ugly, it works. I have cleaned up the string creation code and added it into a category.

DDXMLNode+CDATA.h:

#import <Foundation/Foundation.h>
#import "DDXMLNode.h"

@interface DDXMLNode (CDATA)

/**
 Creates a new XML element with an inner CDATA block
 <name><![CDATA[string]]></name>
 */
+ (id)cdataElementWithName:(NSString *)name stringValue:(NSString *)string;

@end

DDXMLNode+CDATA.m:

#import "DDXMLNode+CDATA.h"
#import "DDXMLElement.h"
#import "DDXMLDocument.h"

@implementation DDXMLNode (CDATA)

+ (id)cdataElementWithName:(NSString *)name stringValue:(NSString *)string
{
    NSString* nodeString = [NSString stringWithFormat:@"<%@><![CDATA[%@]]></%@>", name, string, name];
    DDXMLElement* cdataNode = [[DDXMLDocument alloc] initWithXMLString:nodeString
                                                               options:DDXMLDocumentXMLKind
                                                                 error:nil].rootElement;
    return [cdataNode copy];
}

@end

The code is also available in this gist.

Community
  • 1
  • 1
Imre Kelényi
  • 22,113
  • 5
  • 35
  • 45
0

Found a workaround myself - the idea is basically to disguise the CDATA as a new XML Doc. Some code that works:

+(DDXMLElement* ) createCDataNode:(NSString*)name value:(NSString*)val {

    NSMutableString* newVal = [[NSMutableString alloc] init];
    [newVal appendString:@"<"];
    [newVal appendString:name];
    [newVal appendString:@">"];
    [newVal appendString:@"<![CDATA["];
    [newVal appendString:val];
    [newVal appendString:@"]]>"];
    [newVal appendString:@"</"];
    [newVal appendString:name];
    [newVal appendString:@">"];

    DDXMLDocument* xmlDoc = [[DDXMLDocument alloc] initWithXMLString:newVal options:DDXMLDocumentXMLKind error:nil];

    return [[xmlDoc rootElement] copy];
}

GEEZ! This is just something I would consider to be a "dirty hack". It works but it does not feel right. I would appreciate a "good" solution to this.

moq
  • 65
  • 6