【问题标题】:Objective-C: Convert TBXML element to NSStringObjective-C:将 TBXML 元素转换为 NSString
【发布时间】:2014-03-03 11:43:25
【问题描述】:

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

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

【问题讨论】:

    标签: ios objective-c tbxml


    【解决方案1】:

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

    TBXMLElement *root = tbxml.rootXMLElement;
    
    NSString *stringFromXML = [TBXML textForElement:root];
    
    NSLog(@"XML as String: %@",stringFromXML);
    

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

    在 TBXML 上使用 class 方法来提取根元素的“文本”,并将其存储在 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));  
    }
    

    问候, 约翰

    【讨论】:

    • 这在我的情况下不起作用,因为 xml 可以深入几个级别。 textForElement 方法只会查找给定元素的实际文本值。在我的情况下(可能是大多数情况下)XML 深入并且它是动态的 - 并不总是具有相同的子元素。基本上,这会为我注销一个空字符串。
    • @ChillY 我已经用一个代码示例更新了我的答案,它可以让你弹出每个元素。你可以用它来构建你的 NSString。
    • 更新的答案,是的,我将能够像这样动态地浏览所有元素,但是对于这样一个简单的任务来说,工作量太大了。我宁愿希望,有一种方法可以直接从响应中获取响应字符串,而不是将 TBXML 元素作为 init 的响应。
    • @ChillY 你看过 NSXMLParser 吗?
    • 我还没有,因为我的整个应用程序已经使用了 TBXML。现在更换解析器将非常耗时。虽然如果没有办法在 TBXML 中获取字符串形式的元素,我想我别无选择,会对 TBXML 感到失望
    猜你喜欢
    • 2012-10-06
    • 2011-12-04
    • 2011-01-24
    • 2011-09-18
    • 2020-10-26
    • 2016-12-17
    • 2014-10-25
    • 2010-12-22
    • 2011-07-05
    相关资源
    最近更新 更多