我正在为iOS创建一个应用程序,它需要创建一个XML文档。我通过KissXML做到这一点。XML的一部分如下所示
<ISIN><![CDATA[12345678]]></ISIN>我在KissXML中找不到任何选项来创建CDATA部分。只需添加一个带有CDATA内容的字符串作为文本,将导致转义特殊字符,如<和>。谁能给我一个关于如何用KissXML编写CDATA的提示?
发布于 2012-11-21 21:37:56
尽管the solution by @moq很难看,但它还是可以工作的。我已经清理了字符串创建代码,并将其添加到一个类别中。
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;
@endDDXMLNode+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代码也可以在这个gist中找到。
发布于 2012-08-02 20:57:41
我自己找到了一个变通办法--这个想法基本上就是把CDATA伪装成一个新的XML文档。以下是一些有效的代码:
+(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];
}天哪!这只是我认为是一个“肮脏的黑客”。它起作用了,但感觉不对劲。我希望能有一个“好”的解决方案。
https://stackoverflow.com/questions/11773890
复制相似问题