iPhone开发 - 生成XML文件
答
<?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(@"========================");
}
}
答
尝试开源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>
你想究竟是什么实现?如果您只想将简单的字典/数组转换为XML格式的字符串,那么它只需要几行代码。如果你需要更复杂的东西,那么我相信有一些ope-source库。如果你想将自己的对象转换为特定的XML,那么我想你将不得不手动编译XML字符串... – 2010-09-23 00:53:34
-1模糊。你想要*任何* XML文件,通用的XML编写器或特定的XML格式? – 2010-09-23 03:00:42
在我的问题中,我说过“一个XML文件或字符串”,它表示任何类型的XML文件或字符串。 – Claudio 2010-09-23 04:57:26