Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two xml files in Objective-C

I have two xml files (a.xml and b.xml) in my file system (iPhone). Now I want to know if these files contain exactly the same data. Most of the time, this comparison would be true, because b.xml is the result of a copyItemAtPath: operation. Unless it is overwritten by newer information. What would be the most efficient way to compare these files?

  1. I could read the contents of the files as strings and then compare the strings
  2. I could parse the files and compare some key elements
  3. I guess there is a very blunt way, that doesn't need to interpret the file, but allows me to compare on a lower level.

Any suggestion is very welcome.

Thanks ahead

Sjakelien

Update:

I ended up doing this:

oldData = [NSData dataWithContentsOfFile:PathToAXML];
newData = [NSData dataWithContentsOfFile:PathToBXML];

and then compare it with:

[newData isEqualToData:oldData];

The question is still: is that more efficient than:

oldData = [NSString dataWithContentsOfFile:PathToAXML];
newData = [NSString dataWithContentsOfFile:PathToBXML];

[newData isEqualToString:oldData];
like image 977
Sjakelien Avatar asked Jul 02 '09 14:07

Sjakelien


3 Answers

You could also use:

NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr contentsEqualAtPath:PathToAXML andPath:PathToBXML])
  NSLog (@"File contents match");
else
  NSLog (@"File contents do not match");
like image 94
mahlzeit Avatar answered Oct 17 '22 05:10

mahlzeit


One alternative to comparing the file contents is to track the file modification date -- if it's later than the date you created the copy, you might assume that it has been updated.

See fileAttributesAtPath:traverseLink: in the NSFileManager class.

like image 32
Daniel Dickison Avatar answered Oct 17 '22 04:10

Daniel Dickison


BOOL filesAreEqual = [[NSData dataWithContentsOfMappedFile:file1] isEqual:[NSData dataWithContentsOfMappedFile:file2]];
like image 41
Nikolai Ruhe Avatar answered Oct 17 '22 06:10

Nikolai Ruhe