简体   繁体   English

Objective-C:将TBXML元素转换为NSString

[英]Objective-C: Convert TBXML element to NSString

The problem is, that I get a TBXML element back from initWithURL method of TBXML class. 问题是,我从TBXML类的initWithURL方法获得了TBXML元素。 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. 我想按原样保存此TBXML文档,以便在用户离线时也可以对其进行解析,但是我似乎找不到找到获取整个对象的NSString值的方法。

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. 由于我是Objective-C的新手,所以这也可能真的很容易,因为我没有看到其他任何问题。 I hope you can help me and that this answer could be helpful for others. 希望您能对我有所帮助,希望这个答案对其他人有所帮助。

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': 我个人不会使用TBXML,它又旧又笨拙,而且Apple拥有自己的NSXMLParser类,但是,假设您有一个名为'tbxml'的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. 在这里,我要做的只是根据您的情况获取整个文档的“ root”元素。

Using a class method on TBXML to extract the 'text' for the root element, and store this in an NSString. 在TBXML上使用方法提取根元素的“文本”,并将其存储在NSString中。

You can then use whatever method you'd like to store this NSString or it's value. 然后,您可以使用任何想要存储此NSString或其值的方法。

To traverse an unknown or dynamic XML input: 要遍历未知或动态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));  
}

Regards, John 问候,约翰

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM