我遇到问题包括 TBXML在我的项目中。
guide告诉我包含四个文件,
TBXML.h
、TBXML.m
、NSDataAdditions.h
和NSDataAdditions.m
,但在 the Github repo 中找不到后两者.我尝试运行示例项目 TBXML-Books希望复制 TBXML 是如何导入到项目中的,但它也没有在 Xcode 5 中成功构建。它找不到
libTBXML-iOS.a
。
有人帮忙吗?提前致谢。
最佳答案
将 TBXML 包含到您的项目中
获取
TBXML.h
和TBXML.m
来自 the Github repo并将它们添加到您的项目中。这两个是您唯一需要的文件。在项目的 Target > Build Phases 中,添加编译器标志
-fno-objc-arc
至TBXML.m
.
加载 XML 文档
TBXML *sourceXML = [[TBXML alloc] initWithXMLFile:@"dictionary.xml" error:nil];
您可以使用其他 init 实例方法进行 alloc-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];
遍历未知元素/属性
如果我想打印出每个 <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
的事情,如图the old guide .你也可以只看TBXML.h
了解如何去做。
关于ios - 更新了适用于 iOS 7 的 TBXML : How to include TBXML in Xcode 5, 的指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277203/