0

问题是,我从 TBXML 类的 initWithURL 方法中得到了一个 TBXML 元素。我想按原样保存这个 TBXML 文档,以便以后在用户离线时解析它,但我似乎找不到获取整个对象的 NSString 值的方法。

由于我是 Objective-C 的新手,这可能也很容易,因为我没有看到任何其他问题。我希望你能帮助我,这个答案可能对其他人有帮助。

4

1 回答 1

0

我个人不会使用 TBXML,它又旧又笨重,而且 Apple 有它自己的NSXMLParser类,但是你可以这样做,假设你有一个名为 'tbxml' 的 TBXML 实例:

TBXMLElement *root = tbxml.rootXMLElement;

NSString *stringFromXML = [TBXML textForElement:root];

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

我在这里所做的只是获取“根”元素,基本上是整个文档。

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

问候,约翰

于 2014-03-03T12:00:06.933 回答