TBXMLiOS的轻量级XML解析库

联合创作 · 2023-09-27

TBXML是一个用于iOS上的解析速度非常快的轻量级XML解析库。提供了非常简洁的接口,使用起来很简单。

它提供了可以通过文件路径、URL、XML文件内容、内容字符串等方式载入XML文件,提供了获取XML节点和属性值的方法,以及一个遍历节点的方法。不过TBXML只提供了读的功能。

初始化和释放TBXML

TBXML* tbxml =[ [[TBXML alloc] initWithXMLFile:@"file.xml"] retain];

一定要在后面加上retain,要不运行app时,会出现非法访问的错误。

使用完毕后,注意释放:

[tbxml release];

使用递归方法遍历所有节点和属性的例子

- (void) traverseElement:(TBXMLElement *)element {
    
    do {
        // 显示XML元素名称
        NSLog(@"%@",[TBXML elementName:element]);
        
        // 获取到当前节点的第一个属性
        TBXMLAttribute * attribute = element->firstAttribute;
        
        // if attribute is valid
        while (attribute) {
            // 在log窗口中显示属性的名称和值
            NSLog(@"%@->%@ = %@",[TBXML elementName:element],[TBXML attributeName:attribute], [TBXML attributeValue:attribute]);
            
            // 获取下一个属性
            attribute = attribute->next;
        }
        
        // 递归遍历下一个子元素
        if (element->firstChild) [self traverseElement:element->firstChild];
                                  
    // 获取同级元素
    } while ((element = element->nextSibling));  
}

浏览 6
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报