IPhone开发 - 生成XML文件

时间:2010-09-23 00:38:30

标签: objective-c ios xml cocoa-touch

这里有人知道如何在iPhone中生成XML文件或字符串吗?

2 个答案:

答案 0 :(得分:1)

尝试开源XML stream writer for iOS

  • 用Objective-C编写,单个.h。和.m文件
  • 一个@protocol用于名称空间支持,一个用于不用

示例:

// allocate serializer
XMLWriter* xmlWriter = [[XMLWriter alloc]init];

// start writing XML elements
[xmlWriter writeStartElement:@"Root"];
[xmlWriter writeCharacters:@"Text content for root element"];
[xmlWriter writeEndElement];

// get the resulting XML string
NSString* xml = [xmlWriter toString];

这将生成以下XML字符串:

<Root>Text content for root element</Root>

答案 1 :(得分:0)

<?xml version="1.0" encoding="UTF-8"?> <parent>
<child name="James"> <age>10</age> <sex>male</sex>
</child> </parent>
</xml>
像我使用这个xml一样 写入.h文件........

#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController <NSXMLParserDelegate> {
 @public
}
NSXMLParser *myXMLParser;
@property (nonatomic, retain) NSXMLParser *myXMLParser;
@end
write in .m file
- (void)viewDidLoad { [super viewDidLoad];
NSBundle *mainBundle = [NSBundle mainBundle];
 NSString *xmlFilePath = [mainBundle pathForResource:@"MyXML" ofType:@"xml"];
if ([xmlFilePath length] == 0){ /* The file could not be found in the resources folder.
}
 return;
/* Let's see if the XML file exists... */
 NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:xmlFilePath] == NO){
/* The XML file doesn't exist, we double checked this just to make sure we don't leave any stones unturned. You can now throw an error/exception here or do other appropriate processing */
NSLog(@"The file doesn't exist.");
 [fileManager release]; 
return;
[fileManager release];
/* Load the contents of the XML file into an NSData */ NSData *xmlData = [NSData dataWithContentsOfFile:xmlFilePath];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
self.myXMLParser = xmlParser; [xmlParser release];
[self.myXMLParser setDelegate:self];
if ([self.myXMLParser parse] == YES){
/* Successfully started to parse */ } else {
}
/* Failed to parse. Do something with this error */ 
NSError *parsingError = [self.myXMLParser parserError]; 
NSLog(@"%@", parsingError);

- (void)    parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName

namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
NSLog(@"Element Name = %@", elementName); 
NSLog(@"Number of attributes = %lu",(unsigned long)[attributeDict count]); 
if ([attributeDict count] > 0)
{
NSLog(@"Attributes dictionary = %@", attributeDict); 
NSLog(@"========================");
}
}