开发者

Objective-C XML manipulate as NSString is safe?

开发者 https://www.devze.com 2023-03-21 08:33 出处:网络
Is converting an XML to NSString from NSData, then manipulate string and convert it back to NSData 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 libr开发者_如何学Caries. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消