欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

XML的解析 DOM解析

程序员文章站 2022-05-28 23:45:52
...

参考上一篇的XML数据,上次我们使用的SAX解析。
http://blog.csdn.net/lee727n/article/details/73271916
这次我们通过DOM解析。
XML的解析 DOM解析
软件结构与上一篇一样,需要引入TBXML第三方类。用来做DOM解析
核心代码BookXMLParser.m中的逻辑

+(NSArray *)parseBookWithFileName:(NSString *)name{

    NSMutableArray *books = [NSMutableArray array];

    TBXML *tbXML = [[TBXML alloc]initWithXMLFile:name fileExtension:@"xml" error:nil];

    TBXMLElement *booksEle = tbXML.rootXMLElement;

    TBXMLElement *bookEle = [TBXML childElementNamed:@"book" parentElement:booksEle];

    while (bookEle) {

        Book *book = [Book new];
        book.bookID = [TBXML valueOfAttributeNamed:@"bookID" forElement:bookEle];

        TBXMLElement *titleEle = [TBXML childElementNamed:@"title" parentElement:bookEle];
        TBXMLElement *pageEle = [TBXML childElementNamed:@"page" parentElement:bookEle];
        TBXMLElement *authorEle = [TBXML childElementNamed:@"author" parentElement:bookEle];
        TBXMLElement *priceEle = [TBXML childElementNamed:@"price" parentElement:bookEle];

        book.price = [TBXML textForElement:priceEle];
        book.title = [TBXML textForElement:titleEle];
        book.page = [TBXML textForElement:pageEle];
        book.author = [TBXML textForElement:authorEle];

        [books addObject:book];

        //查找下一个兄弟标签
        bookEle = [TBXML nextSiblingNamed:@"book" searchFromElement:bookEle];
    }
    return books;
}

相对于上一种方式是不是显得更高效,代码更简洁。这就是DOM解析,将所有数据拿到内存中组成树形结构再解析。效率高。只是消耗内存