NSXML replacing “<” with “%lt;”

这一生的挚爱 提交于 2019-12-11 09:48:31

问题


I see there are other questions related to this, but none using NSXML.

So, I'm constructing an XML document from scratch using NSXML and when I create a NSXMLNode with a string value, all the "<" characters in that string are replaced with "& lt;" when I output the node, or save it to a file.

Example:

 NSXMLNode *description = [NSXMLNode elementWithName:@"description"
                               stringValue:@"<![CDATA[Some Description</a>]]>"];

Then when I do

 NSLog(@"description: %@", description);

I get the node with all the '<' characters replaced with "& lt;". However when I do

 NSLog(@"description string value: %@", [description stringValue]);

I get the correct string output. This XML document is going to be saved as a KML file for google earth, and google earth gives me an error when it finds the "& lt;" token. Any idea how to make NSXML just output the '<'? I'm using OSX 10.6 and XCode 3.2 btw.


回答1:


There's a special options flag for indicating CDATA that will help here. The trick is to let cocoa write the <![CDATA[ and ]] bookends for you:

NSXMLNode *cdata = [[[NSXMLNode alloc] initWithKind:NSXMLTextKind
                                            options:NSXMLNodeIsCDATA] autorelease];
[cdata setStringValue:@"Some CDATA Description"];

NSXMLElement *description = [NSXMLNode elementWithName:@"description"];
[description addChild:cdata];

NSLog(@"description: %@", description);

// yields: <description><![CDATA[Some CDATA Description]]></description>

To obtain a string with the angle brackets intact:

NSString *output = [description XMLString];


来源:https://stackoverflow.com/questions/1813503/nsxml-replacing-with-lt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!