1

I'm having problems including TBXML in my project.

  1. The guide tells me to include four files, TBXML.h, TBXML.m, NSDataAdditions.h, and NSDataAdditions.m, but the latter two are nowhere to be found in the Github repo.

  2. I tried running the sample project TBXML-Books in the hopes of copying how TBXML was imported into the project, but it doesn't build successfully in Xcode 5 either. It can't find libTBXML-iOS.a.

Anybody help? Thanks in advance.

4

2 回答 2

6

将 TBXML 包含到您的项目中

  1. Github repo获取TBXML.h和添加它们到你的项目中。这两个是您唯一需要的文件。TBXML.m

  2. 在项目的 Target > Build Phases 中,将编译器标志添加-fno-objc-arcTBXML.m.

加载 XML 文档

TBXML *sourceXML = [[TBXML alloc] initWithXMLFile:@"dictionary.xml" error:nil];

您可以将 alloc-init 与其他 init 实例方法一起使用,或者使用类方法样式(我没有包括已弃用的方法):

- (id)initWithXMLString:(NSString*)aXMLString error:(NSError **)error;
- (id)initWithXMLData:(NSData*)aData error:(NSError **)error;
- (id)initWithXMLFile:(NSString*)aXMLFile error:(NSError **)error;
- (id)initWithXMLFile:(NSString*)aXMLFile fileExtension:(NSString*)aFileExtension error:(NSError **)error;

+ (id)newTBXMLWithXMLString:(NSString*)aXMLString error:(NSError **)error;
+ (id)newTBXMLWithXMLData:(NSData*)aData error:(NSError **)error;
+ (id)newTBXMLWithXMLFile:(NSString*)aXMLFile error:(NSError **)error;
+ (id)newTBXMLWithXMLFile:(NSString*)aXMLFile fileExtension:(NSString*)aFileExtension error:(NSError **)error;

示例 XML 结构

<dictionary>
    <entry id="">
        <text></text>
    </entry>

    <entry id="">
        <text></text>
    </entry>
</dictionary>

提取元素

TBXMLElement *rootElement = sourceXML.rootXMLElement;
TBXMLElement *entryElement = [TBXML childElementNamed:@"entry" parentElement:rootElement];

提取属性

NSString *id = [TBXML valueOfAttributeNamed:@"id" forElement:entryElement];

提取元素文本

TBXMLElement *textElement = [TBXML childElementNamed:@"text" parentElement:entryElement];
NSString *text = [TBXML textForElement:textElement];

遍历未知元素/属性

如果我想打印出 every 内每个<text>元素内的文本<entry>,这就是我要做的:

TBXML *sourceXML = [[TBXML alloc] initWithXMLFile:@"dictionary.xml" error:nil];
TBXMLElement *rootElement = sourceXML.rootXMLElement;
TBXMLElement *entryElement = [TBXML childElementNamed:@"entry" parentElement:rootElement];

do {
    TBXMLElement *textElement = [TBXML childElementNamed:@"text" parentElement:entryElement];
    NSString *word = [TBXML textForElement:textElement];
    NSLog(@"%@", word);
} while ((entryElement = entryElement->nextSibling) != nil);

我没有亲自尝试过遍历属性,但我假设您可以执行类似的操作entryElement->firstAttribute,如旧指南中所示。你也可以看看TBXML.h如何去做。

于 2013-10-09T17:51:25.057 回答
2

如果您还没有,我建议您使用 cocoapods。

http://cocoapods.org/?q=tbxml

于 2013-10-09T16:17:42.340 回答