ChillY
ChillY

Reputation: 125

Objective-C: Convert TBXML element to NSString

The problem is, that I get a TBXML element back from initWithURL method of TBXML class. I'd like to save this TBXML document as it is, in order to parse it afterwards, when the user is offline as well, but I can't seem to find a method to get the NSString value of the whole object.

As I am new to Objective-C, this might be something really easy as well, as I didn't see any other problems as these. I hope you can help me and that this answer could be helpful for others.

Upvotes: 0

Views: 1002

Answers (1)

Woodstock
Woodstock

Reputation: 22936

I personally wouldn't use TBXML, it's old and clunky plus Apple has it's own NSXMLParser class, however you can do it like this, assuming you have an TBXML instance called 'tbxml':

TBXMLElement *root = tbxml.rootXMLElement;

NSString *stringFromXML = [TBXML textForElement:root];

NSLog(@"XML as String: %@",stringFromXML);

All that I'm doing here is getting the 'root' element basically the whole document in your case.

Using a class method on TBXML to extract the 'text' for the root element, and store this in an NSString.

You can then use whatever method you'd like to store this NSString or it's value.

To traverse an unknown or dynamic XML input:

- (void)loadUnknownXML {
// Load and parse the test.xml file
tbxml = [[TBXML tbxmlWithXMLFile:@"test.xml"] retain];

// If TBXML found a root node, process element and iterate all children
if (tbxml.rootXMLElement)
[self traverseElement:tbxml.rootXMLElement];


- (void) traverseElement:(TBXMLElement *)element {

do {
// Display the name of the element
NSLog(@"%@",[TBXML elementName:element]);

// Obtain first attribute from element
TBXMLAttribute * attribute = element->firstAttribute;

// if attribute is valid
while (attribute) {
// Display name and value of attribute to the log window
NSLog(@"%@->%@ = %@",
                    [TBXML elementName:element],
                    [TBXML attributeName:attribute],
                    [TBXML attributeValue:attribute]);

// Obtain the next attribute
attribute = attribute->next;
}

// if the element has child elements, process them
if (element->firstChild) 
            [self traverseElement:element->firstChild];

// Obtain next sibling element
} while ((element = element->nextSibling));  
}

Regards, John

Upvotes: 0

Related Questions