我正在尝试从 here 中提取天气信息在 iPhone 上使用 Xpath。截至目前,它解析了所有数据,但我一直困惑于如何提取内容并将其显示在表格中。 这是我到目前为止所拥有的:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[ @"http://aviationweather.gov/adds/metars/?station_ids=1234&std_trans=translated&chk_metars=on&hoursStr=most+recent+only&submitmet=Submit"stringByReplacingOccurrencesOfString:@"1234" withString:self.title]]];
TFHpple * doc = [[TFHpple alloc] initWithHTMLData:data];
NSArray * elements = [doc searchWithXPathQuery:@"//table[1]//tr"];
NSLog(@"%@", elements);
TFHppleElement * element = [elements objectAtIndex:0];
[element content]; // Tag's innerHTML
[element tagName]; // "a"
[element attributes]; // NSDictionary of href, class, id, etc.
[element objectForKey:@"href"]; // Easy access to single attribute
如果有人需要查看到目前为止的输出内容,请告诉我。
谢谢, 安德鲁
最佳答案
我遇到了同样的问题,我已经到了你的地步,但无处可去,但我最终实现了这段代码。希望它能有所帮助,要使其正常工作,仍然需要一点点,但要根据我开发的应用程序的性质,这就是我能为您提供的一切。它并不多,只是您真正需要的代码的实际实现。
#import "XPathQuery.h"
NSMutableArray *weatherArray = [[NSMutableArray arrayWithArray:0]retain]; // Initilize the NSMutableArray can also be done with just an NSArray but you will have to change the populateArray method.
NSString *xPathLookupQuery = @"//table[1]//tr"; // Path in xml
nodes = PerformXMLXPathQuery(data, xPathLookupQuery); // Pass the data in that you need to search through
[self populateArray:weatherArray fromNodes:nodes]; // To populate multiple values into array.
session = [[self fetchContent:nodes] retain]; // To populate a single value and returns value.
- (void)populateArray:(NSMutableArray *)array fromNodes:(NSArray *)nodes
{
for (NSDictionary *node in nodes) {
for (id key in node) {
if ([key isEqualToString:@"nodeContent"]) {
[array addObject:[node objectForKey:key]];
}
}
}
}
您只需要上面的代码或下面的代码,除非您两者都需要。
- (NSString *)fetchContent:(NSArray *)nodes
{
NSString *result = @"";
for (NSDictionary *node in nodes) {
for (id key in node) {
if([key isEqualToString:@"nodeContent"]) {
result = [node objectForKey:key];
}
}
}
return result;
}
关于iphone - 如何在iPhone上显示Xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8857250/