所以我松散地跟着this tutorial将HTML解析为Master / Detail App。
我正在尝试将NSArray更改为NSString,但是唯一的数组元素(只有一个元素)似乎没有被完全解析。
我的代码:
viewcontroller.h:
#import <UIKit/UIKit.h>
@interface viciViewController : UIViewController {
IBOutlet UITextView *label;
IBOutlet UITextField *textfield;
IBOutlet UITextView *translation;
IBOutlet UIButton *transButton;
BOOL connectedToInternet;
}
-(IBAction)translateButton;
@end
viewcontroller.m:
#import "viciViewController.h"
#import "TFHpple.h"
@interface viciViewController ()
@end
@implementation viciViewController
- (BOOL)connectedToInternet
{
NSURL *url=[NSURL URLWithString:@"http://www.google.com"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL];
return ([response statusCode]==200)?YES:NO;
}
-(IBAction)translateButton {
if ([self connectedToInternet] == NO)
{
translation.text = @"Sorry, you need an internet connection to translate.";
// Not connected to the internet
}
else
{
// Connected to the internet
[textfield resignFirstResponder];
NSString *toTranslate = self->textfield.text;
NSString *url = [NSString stringWithFormat:@"http://www.archives.nd.edu/cgi-bin/wordz.pl?keyword=%@", toTranslate];
NSURL *translationUrl = [NSURL URLWithString:(url)];
NSData *translationHtmlData = [NSData dataWithContentsOfURL:translationUrl];
TFHpple *translationParser = [TFHpple hppleWithHTMLData:translationHtmlData];
// 3
NSString *translationXpathQueryString = @"/html/body/pre";
NSArray *translationOutput = [translationParser searchWithXPathQuery:translationXpathQueryString];
NSString * result = [[translationOutput valueForKey:@"description"] componentsJoinedByString:@""];
NSLog(@"Response %@", result);
}
控制台中的日志显示:
Response {
nodeChildArray = (
{
nodeContent = "\nsemper ADV POS \nsemper ADV [XXXAX] \nalways;\n\n";
nodeName = text;
}
);
nodeName = pre;
raw = "<pre>\nsemper ADV POS \nsemper ADV [XXXAX] \nalways;\n\n</pre>";
}
所以,问题:是否可以将只是 nodeContent作为NSString并将\n
转换为回车?
感谢您的帮助!
答案 0 :(得分:1)
TFHppleElement
正是如此:
替换您的代码
中的以下行NSString * result = [[translationOutput valueForKey:@"description"] componentsJoinedByString:@""];
NSLog(@"Response %@", result);
以下内容:
NSString *translatedString = ((TFHppleElement *)translationOutput[0]).firstChild.content;
NSLog(@"%@", translatedString);
不要忘记加入TFHppleElement.h
<强>输出强>
如果您发送semper
,translatedString
中存储的已解析结果为
semper ADV POS
semper ADV [XXXAX]
总是;
答案 1 :(得分:0)
所以你有一个字典,向它询问nodeChildArray对象,询问该数组的第一个对象,向该字典询问其节点内容。现在你有了一个字符串。使用NSString方法在给定子字符串(@“\ n”,两个反斜杠)的情况下分解字符串,现在获得一个字符串数组。迭代所有,再次使用字符串方法删除前导和尾随空格。如果字符串有长度,您可以再次获取由空格分隔的字符串数组,或使用NSScanner来执行此操作。