Does anybody here know how to generate a 开发者_StackOverflow社区XML file or string in the iPhone?
Try the open source XML stream writer for iOS:
- Written in Objective-C, a single .h. and .m file
- One @protocol for namespace support and one for without
Example:
// 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];
This produces the following XML string:
<Root>Text content for root element</Root>
<?xml version="1.0" encoding="UTF-8"?> <parent>
<child name="James"> <age>10</age> <sex>male</sex>
</child> </parent>
</xml>
like i use this xml write in .h file........
#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(@"========================");
}
}
精彩评论