问题
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