我正在开发一款需要使用XML文件的iPhone应用程序。 我知道如何解析XML,现在我需要获取用户输入的信息, 并将其写入xml(相同的或新的), 我怎样才能实现它?
我查看谷歌和此处,但部分指南不是很清楚,有些是不赞成使用的方法..
Tnx的帮助!
答案 0 :(得分:3)
创建一个NSMutableString *并以XML方式向其追加数据。
NSMutableString *xmlstring = [[NSMutableString alloc]init];
[xmlstring appendString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"];
[xmlstring appendString:@"<RegistrationXml xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"];
[xmlstring appendString:@"<DataFields>\n"];
[xmlstring appendString:@"<Name>FirstName</Name>\n"];
[xmlstring appendFormat:@"<Value>%@</Value>\n", [self replaceXMLReservedCharactersInString:someString]];
[xmlstring appendString:@"</DataFields>\n"];
[xmlstring appendString:@"</RegistrationXml>\n"];
其中
- (NSString *)replaceXMLReservedCharactersInString:(NSString *)string
{
NSString *result;
result = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
result = [result stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
result = [result stringByReplacingOccurrencesOfString:@">" withString:@">"];
return result;
}
然后通过它...... 如果要将其写入文件,请搜索NSFileManager。
答案 1 :(得分:0)
我最后用过这个,
写入文件:
NSMutableString *xmlString = [[NSMutableString alloc]init];
//Get all data into an NSMutableString
[xmlString appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"];
[xmlString appendString:@"<CATALOG>"];
[xmlString appendString:@"<USER Name=\""];
[xmlString appendString:username];
[xmlString appendString:@"\" FBid=\""];
[xmlString appendString:facebookID];
[xmlString appendString:@"\" email=\""];
[xmlString appendString:email];
[xmlString appendString:@"\"/>\n"];
[xmlString appendString:@"</CATALOG>\n"];
//Write the NSMutableString into the xml file
NSString *savePath = [[NSBundle mainBundle]pathForResource:@"UserDetails" ofType:@"xml"];
[xmlString writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:nil];