利用第三方库XML解析 (TBXML)转化成模型数据

第一部分XML数据
<?xml version="1.0"?>



<authors>
    <author name="DouglasAdams">
        <book title="The Hitchhiker's Guide to the Galaxy11111111" price="15.49">
            <description>
                1111111 Douglas Adams's hapless hero Arthur Dent as he travels the galaxy with his intrepid pal Ford Prefect, getting into horrible messes and generally wreaking hilarious havoc.
            </description>
        </book>
        <book title="The Restaurant at the End of the Universe222222 " price="14.36">
            <description>
                2222222Arthur and Ford, having survived the destruction of Earth by surreptitiously hitching a ride on a Vogon constructor ship, have been kicked off that ship by its commander. Now they find themselves aboard a stolen Improbability Drive ship commanded by Beeblebrox, ex-president of the Imperial Galactic Government and full-time thief.
            </description>
        </book>
    </author>
    <author name="J.K. Rowling">
        <book title="Harry Potter and the Philosopher's Stone" price="119.99">
            <description>
                Harry potter thinks he is an ordinary boy - until he is rescued from a beetle-eyed giant of a man, enrolls at Hogwarts School of Witchcraft and Wizardry, learns to play quidditch and does battle in a deadly duel.
            </description>
        </book>
        <book title="Harry Potter and the Chamber of Secrets" price="8.99">
            <description>
                When the Chamber of Secrets is opened again at the Hogwarts School for Witchcraft and Wizardry, second-year student Harry Potter finds himself in danger from a dark power that has once more been released on the school.
            </description>
        </book>
        <book title="Harry Potter and the Prisoner of Azkaban" price="12.99">
            <description>
                Harry Potter, along with his friends, Ron and Hermione, is about to start his third year at Hogwarts School of Witchcraft and Wizardry. Harry can't wait to get back to school after the summer holidays. (Who wouldn't if they lived with the horrible Dursleys?) But when Harry gets to Hogwarts, the atmosphere is tense. There's an escaped mass murderer on the the loose, and the sinister prison guards of Azkaban have been called in to guard the school.
            </description>
        </book>
    </author>
</authors>

第二部分:数据模型(作者模型)

//
//  ZKZAuthor.h
//  使用TBXml解析
//
//  Created by 张凯泽 on 16/2/22.
//  Copyright © 2016年 rytong_zkz. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ZKZAuthor : NSObject
@property(nonatomic,copy)NSString *authorName;//作者名字
@property(nonatomic,strong)NSMutableArray *books;//各种书籍


@end

第三部分数据模型(书籍模型)


//
//  ZKZBook.h
//  使用TBXml解析
//
//  Created by 张凯泽 on 16/2/22.
//  Copyright © 2016年 rytong_zkz. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ZKZBook : NSObject
@property(nonatomic,copy)NSString *price;//书的价格
@property(nonatomic,copy)NSString *title;//书的名字
@property(nonatomic,copy)NSString *descriptionStr;//书的表述

@end
第四部分解析XML主体
//  ViewController.m
//  使用TBXml解析
//
//  Created by 张凯泽 on 15/11/24.
//  Copyright © 2015年 rytong_zkz. All rights reserved.
//

#import "ViewController.h"
#import "TBXML.h"
#import "ZKZAuthor.h"
#import "ZKZBook.h"
@interface ViewController ()
@property(nonatomic,strong)TBXML *tbXml;
//@property(nonatomic,strong)NSMutableArray *books;//书籍的数组
@property(nonatomic,strong)NSMutableArray *authors;//作者数组

@end

@implementation ViewController
@synthesize tbXml;
@synthesize authors;
- (void)viewDidLoad {
    [super viewDidLoad];
    NSError *error;
    tbXml = [[TBXML alloc]initWithXMLFile:@"books2.xml" error:&error];
    //[self startTBXml:tbXml];
    //[self dealUnknow:tbXml];
    //把XML数据转化成模型
    [self loadArticles:tbXml];
    
    
    
}
-(void)startTBXml:(TBXML*)tbXml
{
    
    TBXMLElement *root = tbXml.rootXMLElement;
    TBXMLElement *author = [TBXML childElementNamed:@"author" parentElement:root];
    NSString *name = [TBXML valueOfAttributeNamed:@"name" forElement:author];
    NSLog(@"author:%@", name);
    TBXMLElement *book = [TBXML childElementNamed:@"book" parentElement:author];
    NSString *title = [TBXML valueOfAttributeNamed:@"title" forElement:book];
    NSLog(@"title:%@", title);
    NSString *price = [TBXML valueOfAttributeNamed:@"price" forElement:book];
    NSLog(@"price:%@", price);
    TBXMLElement *descriptionElem = [TBXML childElementNamed:@"description" parentElement:book];
    NSString * description = [TBXML textForElement:descriptionElem];
    NSLog(@"author:%@", description);
}

- (void)dealUnknow:(TBXML *)tbx {
    if (tbx.rootXMLElement) {
        TBXMLElement *element = tbx.rootXMLElement;
        [self recurrence:element];
    }
    else {
        NSLog(@"Format Error!");
    }
    tbXml = nil;
}
//递归子方法
- (void)recurrence:(TBXMLElement *)element {
    do {
        
        NSLog(@"<%@>:{%@}",[TBXML elementName:element], [TBXML textForElement:element]);// Display the name of the element
        
        //迭代处理所有属性
        TBXMLAttribute * attribute = element->firstAttribute;
        while (attribute) {
            //显示
            NSLog(@"___****___<%@>->[%@ = %@]", [TBXML elementName:element], [TBXML attributeName:attribute], [TBXML attributeValue:attribute]);
            
            //迭代
            attribute = attribute->next;
        }
        
        //递归处理子树
        if (element->firstChild) {
            [self recurrence:element->firstChild];
        }
        
        //迭代处理兄弟树
    } while ((element = element->nextSibling)); 
}
- (void)loadArticles:(TBXML*)tbxml {
    TBXMLElement *root = tbxml.rootXMLElement;//articles
    if (root)
    {
        authors = [NSMutableArray array];//作者数组
        TBXMLElement *channel = [TBXML childElementNamed:@"author" parentElement:root];//作者
        
        while (channel) {
            NSString *name = [TBXML valueOfAttributeNamed:@"name" forElement:channel];//作者名字
            ZKZAuthor * author = [[ZKZAuthor alloc]init];//创建作者模型
            author.authorName = name;
            if (channel)
            {
                NSMutableArray *books = [NSMutableArray array];//书籍数组
                TBXMLElement *item = [TBXML childElementNamed:@"book" parentElement:channel];//书籍
                while (item)
                {
                    ZKZBook * book = [[ZKZBook alloc]init];//创建书籍模型
                    //书的名字
                    NSString *title = [TBXML valueOfAttributeNamed:@"title" forElement:item];
                    book.title = title;
                    //书的价格
                    NSString *price = [TBXML valueOfAttributeNamed:@"price" forElement:item];
                    book.price = price;
                    TBXMLElement *descriptionElem = [TBXML childElementNamed:@"description" parentElement:item];//书的描述
                    NSString * description = [TBXML textForElement:descriptionElem];
                    book.descriptionStr = description;
                    [books addObject:book];
                    //寻找下一个书籍
                    item = [TBXML nextSiblingNamed:@"book" searchFromElement:item];
                }
                author.books = books;
            }
            [authors addObject:author];
            //寻找下一个作者
            channel = [TBXML nextSiblingNamed:@"author" searchFromElement:channel];
        }
    }
    for (ZKZAuthor * author  in authors) {
        NSLog(@"authorName = %@",author.authorName);
        for (ZKZBook * book in author.books) {
            NSLog(@"title = %@",book.title);
            NSLog(@"price = %@",book.price);
            NSLog(@"descriptionStr = %@",book.descriptionStr);
        }
    }
    
    tbxml = nil;
}
@end

 

posted @ 2016-02-23 11:21  张凯泽  阅读(589)  评论(0编辑  收藏  举报