Including TBXML into your project
Get
TBXML.h
andTBXML.m
from the Github repo and add them into your project. Those two are the only files you need.In your project's Target > Build Phases, add the compiler flag
-fno-objc-arc
toTBXML.m
.
Loading an XML document
TBXML *sourceXML = [[TBXML alloc] initWithXMLFile:@"dictionary.xml" error:nil];
You can alloc-init with the other init instance methods, or do it class-method style (I didn't include the deprecated methods):
- (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;
Sample XML structure
<dictionary>
<entry id="">
<text></text>
</entry>
<entry id="">
<text></text>
</entry>
</dictionary>
Extracting elements
TBXMLElement *rootElement = sourceXML.rootXMLElement;
TBXMLElement *entryElement = [TBXML childElementNamed:@"entry" parentElement:rootElement];
Extracting attributes
NSString *id = [TBXML valueOfAttributeNamed:@"id" forElement:entryElement];
Extracting element text
TBXMLElement *textElement = [TBXML childElementNamed:@"text" parentElement:entryElement];
NSString *text = [TBXML textForElement:textElement];
Traversing unknown elements/attributes
If I wanted to print out the text inside every <text>
element inside every <entry>
, this is what I'll do:
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);
I haven't personally tried out traversing the attributes but I assume you can do something like entryElement->firstAttribute
, as shown in the old guide. You can also just look at TBXML.h
for how to go about it.