Objective-C XML本地文件解析

//—— ————— —————— ————— —————— — 测试XML解析————— ————————— —————————————————————ios解析思路

//1、获得解析路径
//2、将解析路径转换成UTF8码的字符串类型
//3、使用 GDataXMLDocument 转换成XML类型文件
//4、GDataXMLElement 获得根节点
//5、开始繁琐的解析:根据不同的情况用GDataXMLElement(节点)或NSArray(数组)存放解析数据
//6、找到要的数据,使用stringValue转换数据类型,输出

 

本文的解析是用GDataXML,可以从http://code.google.com/p/gdata-objectivec-client/downloads/list下载“gdata-objective-c client library.”

 

GDataXML解析的具体内容,亲测试有效:

<Books>

   <bookauthor="小王">

        <bookTitle>c语言</bookTitle>

        <bookPublish>清华大学</bookPublish>

        <bookPrise>33</bookPrise>

    </book>

   <bookauthor="小张">

        <bookTitle>IOS编程</bookTitle>

        <bookPublish>北京大学</bookPublish>

        <bookPrise>77</bookPrise>

    </book>

</Books>

开始解析:

- (void)justDoXml

{

    //获得静态路径

    NSString * path = [[NSBundlemainBundle]pathForResource:@"Book"ofType:@"xml"];

    //取得路径中的文件

    NSString * xml = [NSStringstringWithContentsOfFile:pathencoding:NSUTF8StringEncodingerror:nil];

    //转换xml内的数据

    GDataXMLDocument * doc = [[GDataXMLDocumentalloc]initWithXMLString:xmloptions:0error:nil];

    

    //创建根节点

    GDataXMLElement * root = [docrootElement];

    

    //取得根节点root中名字为”book“的数组元素,赋值给bookPo

   NSArray * bookPo = [rootelementsForName:@"book"];//NSArray里包含元素类型必须是一样的

    解析得到数组:

        <bookTitle>c语言</bookTitle>

        <bookPublish>清华大学</bookPublish>

        <bookPrise>33</bookPrise>

 

           <bookTitle>IOS编程</bookTitle>

        <bookPublish>北京大学</bookPublish>

        <bookPrise>77</bookPrise>

    

    //取得数组bookPo中下标为0的节点,赋值给bookIfo

   GDataXMLElement *  bookInfo = [bookPoobjectAtIndex:0];

   解析得到节点:

        <bookTitle>c语言</bookTitle>

        <bookPublish>清华大学</bookPublish>

        <bookPrise>33</bookPrise>


    //取得节点bookInfo中名字为”book“的数组元素,赋值给ifo

   NSArray * ifo = [bookInfoelementsForName:@"bookTitle"];

   解析得到数组:

        <bookTitle>c语言</bookTitle> //这其实是数组


    //取得数组ifo中下标为0的节点,赋值给oneifo

    GDataXMLElement * oneifo = [ifoobjectAtIndex:0];

   解析得到数组中下标为 0 的元素:

         c语言


    //stringValue函数得出oneifo内的数据

   NSString * result = [oneifostringValue];

   NSLog(@"%@",result);

    //之前的步骤完成了解析出一个数据,以下进行便利即可取出所有的数据

   for (int i=0; i<bookPo.count; i++) {

       //打印书名

       GDataXMLElement *  bookInfo = [bookPoobjectAtIndex:i];

        //取得节点bookInfo中名字为”book“的数组元素,赋值给ifo

       NSArray * ifo = [bookInfoelementsForName:@"bookTitle"];

        //取得数组ifo中下标为0的节点,赋值给oneifo

       GDataXMLElement * oneifo = [ifoobjectAtIndex:0];

        //stringValue函数得出oneifo内的数据

       NSString * result = [oneifostringValue];

       NSLog(@"书名=%@",result);

        

        //遍历书的出版社

        //取得节点bookInfo中名字为”book“的数组元素,赋值给ifo

       NSArray * ifo1 = [bookInfoelementsForName:@"bookPublish"];

        //取得数组ifo中下标为0的节点,赋值给oneifo

       GDataXMLElement * oneifo1 = [ifo1objectAtIndex:0];

        //stringValue函数得出oneifo内的数据

       NSString * result1 = [oneifo1stringValue];

       NSLog(@"出版社=%@",result1);

        

        //遍历书的价格(用循环嵌套可让代码看起来更少)

        NSLog(@"价格=%@",[[[bookInfoelementsForName:@"bookPrise"]objectAtIndex:0]stringValue]);


        //遍历书的作者姓名(属性)

        NSLog(@"作者=%@",[[bookInfoattributeForName:@"author"]stringValue]);

    }

}


解析的结果:

2013-05-02 20:40:23.291 TestJosenMySelf[8278:c07] c语言

2013-05-02 20:40:23.291 TestJosenMySelf[8278:c07]书名=c语言

2013-05-02 20:40:23.292 TestJosenMySelf[8278:c07]出版社=清华大学

2013-05-02 20:40:23.292 TestJosenMySelf[8278:c07]价格=33

2013-05-02 20:40:23.292 TestJosenMySelf[8278:c07]作者=小王

2013-05-02 20:40:23.293 TestJosenMySelf[8278:c07]书名=IOS编程

2013-05-02 20:40:23.293 TestJosenMySelf[8278:c07]出版社=北京大学

2013-05-02 20:40:23.293 TestJosenMySelf[8278:c07]价格=77

2013-05-02 20:40:23.294 TestJosenMySelf[8278:c07]作者=小张



【原创】转帖请注明来源,谢谢 -tag 1- 测试无内存泄露 1 创建数据对象() NSMutableDictionary *map = [[NSMutableDictionary alloc]init]; [map setObject:@"a" forKey:@"author"]; [map setObject:@"b" forKey:@"title"]; [map setObject:@"c" forKey:@"content"]; 或者 NSMutableArray *list = [[NSMutableArray alloc]init]; NSMutableDictionary *map1 = [[NSMutableDictionary alloc]init]; [map1 setObject:@"a1" forKey:@"author"]; [map1 setObject:@"b1" forKey:@"title"]; [map1 setObject:@"c1" forKey:@"content"]; [list addObject:map1]; NSMutableDictionary *map2 = [[NSMutableDictionary alloc]init]; [map2 setObject:@"a2" forKey:@"author"]; [map2 setObject:@"b2" forKey:@"title"]; [map2 setObject:@"c2" forKey:@"content"]; [list addObject:map2]; 2 调用封装,声明对象名称及XML模板,组装器会根据XML模板填充数据。 XmlPackage *xmlPackage = [[XmlPackage alloc]init]; NSData *data = [xmlPackage objctPackage:map objectName:@"book1" xmlTemplateName:@"template1"]; 或者 NSData *data = [xmlPackage listPackage:list objectName:@"book1" xmlTemplateName:@"template1"]; 3 返回DATA 4 利用解析解析并展现到UIView 部分代码如下: @implementation XmlPackage @synthesize obj; @synthesize isList; @synthesize xmlString; @synthesize objectName; @synthesize lvUp; @synthesize root; @synthesize buildEnd; -(NSData *)objctPackage:(NSMutableDictionary *)object objectName:(NSString *)name xmlTemplateName:(NSString *)templateName { NSMutableArray *array = [[NSMutableArray alloc]init]; [array addObject:object]; NSData *data = [self listPackage:array objectName:name xmlTemplateName:templateName]; [array release]; return data; } -(NSData *)listPackage:(NSMutableArray *)objects objectName:(NSString *)name xmlTemplateName:(NSString *)templateName { isList = YES; self.objectName = name; NSString *path = [[NSBundle mainBundle] pathForResource:templateName ofType:@"xml"]; NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path]; NSData *xmlData = [file readDataToEndOfFile]; NSXMLParser *xmlRead = [[NSXMLParser alloc] initWithData:xmlData]; [xmlRead setDelegate:self]; [xmlRead parse]; [xmlRead release]; //get dataTemplate for (int i=0;i<[objects count]; i++) { NSMutableDictionary *map = [objects objectAtIndex:i]; XmlNode *node = [[[XmlNode alloc]init]autorelease]; node.nodeName = objectName; [node addChildByMap:map]; [lvUp addChildNode:node]; } //get root's xmlString NSMutableString *x = [self.root getXmlString]; //NSLog(@"%@",x); if ((int)[x length]>0) { return [x dataUsingEncoding:NSUTF8StringEncoding]; } return nil; } - (void)dealloc { [obj release]; [xmlString release]; [objectName release]; [lvUp release]; //[root release]; [super dealloc]; } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ([elementName isEqualToString:objectName]) { buildEnd = YES; }else{ if (!buildEnd) { //create node XmlNode *node = [[XmlNode alloc]init]; node.nodeName = elementName; //dataTemplate building... if (lvUp!=nil) { [lvUp addChildNode:node]; }else{ root = node; } lvUp = node; } } } @end ===== #import "XmlNode.h" @implementation XmlNode @synthesize nodeName; @synthesize nodeValue; @synthesize isLast; @synthesize list; @synthesize xmlString; - (void)dealloc { [nodeName release]; [nodeValue release]; [list release]; [xmlString release]; [super dealloc]; } -(NSString *)getXmlString { xmlString = [[NSMutableString alloc]init]; [xmlString appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"]; [self getNodeStr:self string:xmlString]; return xmlString; } -(void)getNodeStr:(XmlNode *)node string:(NSMutableString *)str { if (node.isLast) { NSString *res = [[NSString alloc]initWithFormat:@"<%@>%@</%@>", node.nodeName, node.nodeValue, node.nodeName]; [str appendString:res]; [res release]; }else{ NSMutableString *a = [[[NSMutableString alloc]init]autorelease]; NSMutableArray *nodelist = [node getChilds]; for (int i=0;i<[nodelist count];i++) { XmlNode *node = [nodelist objectAtIndex:i]; [node getNodeStr:node string:a]; } NSString *res = [[NSString alloc]initWithFormat:@"<%@>%@</%@>", node.nodeName, a, node.nodeName]; [str appendString:res]; [res release]; } } -(void)addChildNode:(XmlNode *)node; { if (list==nil) { list = [[NSMutableArray alloc]init]; } [list addObject:node]; isLast = NO; } -(NSMutableArray *)getChilds { return list; } -(void)addChildByMap:(NSMutableDictionary *)map { NSEnumerator *keys = [map keyEnumerator]; id key; while (key = [keys nextObject]) { XmlNode *node = [[[XmlNode alloc]init]autorelease]; node.isLast = YES; node.nodeName = key; node.nodeValue = [map objectForKey:key]; [self addChildNode:node]; } } @end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值