简体   繁体   中英

Objective-C XML manipulate as NSString is safe?

Is converting an XML to NSString from NSData, then manipulate string and convert it back to NSData is safe?

I heard it is always safer to work with XML Parsing libraries. Can anyone explain why? and at which points I should be careful if I will use that method? is that a possible encoding problem?

The risk is that you'll do this:

  1. Convert an XML to a string
  2. Manipulate the string, and accidentally break the XML.
  3. Convert back, and end up with an invalid XML.

If you work with an XML parsing library, as you can manipulate the elements in a DOM, you won't have the chance of breaking the XML structure and ending up with an invalid XML.

Other than that, if you are careful with the operations you do on the NSString , you'll probably be fine.

Conversion between NSData and NSString is safe as long as you do the conversion with the original encoding.

// example: to NSData and back assuming the original message uses UTF-8
NSData *data = [NSData dataWithBytes:[message UTF8String] length:[message lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSString *string = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];

Parsing XML as string will onnly work with naive documents. If your XML structure doesn't change, if the elements you search for are unique, if the contents are only characters, if there are no CDATA sections in the middle, if there are no namespaces, you are safe. Otherwise your code will get easily confused trying to digest the XML. It's going to be more solid if both the creator and the client of the document abide by the rules set by the XML standard.

If behind all this you are worrying about complexity, it's easy to operate on XML using XPath . If you worry about speed, maybe you could switch to a faster format like JSON if you are in control of XML generation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM