[Cocoa]_[初级]_[使用NSXMLElement 创建一个XML文件]

前端之家收集整理的这篇文章主要介绍了[Cocoa]_[初级]_[使用NSXMLElement 创建一个XML文件]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

场景:未为程序启动的时候配置一些记录文件,保存程序当时的状态。

+(void) CreateXmlFile
{
    NSXMLElement *root =[[NSXMLElement alloc] initWithName:@"group"];
    NSXMLElement *family =[[NSXMLElement alloc] initWithName:@"family" stringValue:@"家人"];
    NSXMLElement *friend =[[NSXMLElement alloc] initWithName:@"friend"];
    NSXMLElement *classmate =[[NSXMLElement alloc] initWithName:@"classmate" stringValue:@"同学"];
    NSXMLElement *worker =[[NSXMLElement alloc] initWithName:@"worker" stringValue:@"同事"];
    NSXMLElement *fellowVillager =[[NSXMLElement alloc] initWithName:@"fellowVillager" stringValue:@"老乡"];
    NSXMLElement *stranger =[[NSXMLElement alloc] initWithName:@"stranger" stringValue:@"陌生人"];
    
    [root addChild:family];
    [root addChild:friend];
    NSXMLElement *item1 =[[NSXMLElement alloc] initWithName:@"item1" stringValue:@"张三"];
    NSXMLElement *item2 =[[NSXMLElement alloc] initWithName:@"item2" stringValue:@"李四"];
    NSXMLElement *item3 =[[NSXMLElement alloc] initWithName:@"item3" stringValue:@"王五"];
    [friend addChild:item1];
    [friend addChild:item2];
    [friend addChild:item3];
    
    [root addChild:classmate];
    [root addChild:worker];
    [root addChild:fellowVillager];
    [root addChild:stranger];
   
    
    NSXMLDocument *xmlRoot =[[NSXMLDocument alloc] initWithRootElement:root];
    [root release];
    NSData *data =[xmlRoot XMLData];
    [data writeToFile:@"/Users/mac/work/pratise/12.xml" atomically:NO];
    [xmlRoot release];
    
    
}

运行结果:

原文链接:https://www.f2er.com/xml/296230.html

猜你在找的XML相关文章