2014-03-03 47 views
0

問題是,我從TBXML類的initWithURL方法中獲得TBXML元素。我想保存這個TBXML文檔,以便在用戶離線時解析它,但我似乎無法找到獲取整個對象的NSString值的方法。Objective-C:將TBXML元素轉換爲NSString

由於我是Objective-C的新手,這可能也很容易,因爲我沒有看到任何其他問題。我希望你能幫助我,而這個答案可能對別人有幫助。

回答

0

我個人不會用TBXML,這是老笨重加上蘋果有它自己的NSXMLParser類,但是你能做到這樣,假設你有一個名爲「TBXML」的TBXML實例:

TBXMLElement *root = tbxml.rootXMLElement; 

NSString *stringFromXML = [TBXML textForElement:root]; 

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

我在這裏所做的只是獲取「root」元素,基本上就是您的案例中的整個文檔。

在TBXML上使用方法爲根元素提取「文本」,並將其存儲在NSString中。

然後,您可以使用任何方法來存儲此NSString或它的值。

要遍歷一個未知的或動態的XML輸入:

- (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)); 
} 

問候, 約翰

+0

這並不在我的情況由於工作,XML可以深入進去幾個層次。 textForElement方法只會查找給定元素的實際文本值。在我的情況下(可能大多數情況下),XML的深入和動態 - 並不總是具有相同的子元素。基本上,這爲我註銷一個空字符串。 – ChillY

+0

@ChillY我用一個代碼示例更新了我的答案,它可以讓你彈出每個元素。你可以用它來構建你的NSString。 – Woodstock

+0

更新後的答案,是的,我將能夠動態地瀏覽所有這些元素,但對於這樣一個簡單的任務來說太空虛了。我很希望,有一種方法可以直接從響應中獲取響應字符串,而不是將TBXML元素作爲init的響應。 – ChillY