c libxml2解析html,简单的libxml2 HTML解析示例,使用Objective-c,Xcode和HTMLparser.h

慕皓君
2023-12-01

请有人向我显示一个使用libxml解析一些

HTML的简单示例.

#import

NSString *html = @"

  • "

"

"

"

"

"

"

"Hello World 1"

"Hello World 2";

1)说我想解析name = input2的输入的值.

应输出“string2value”.

2)说我想解析每个跨标签的class = spantext的内容.

应输出:“Hello World 1”和“Hello World 2”.

我使用本里维斯

HTML Parser来实现我想要的:

NSError *error = nil;

NSString *html =

@"

  • "

"

"

"

"

"

"

"Hello World 1"

"Hello World 2";

HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];

if (error) {

NSLog(@"Error: %@",error);

return;

}

HTMLNode *bodyNode = [parser body];

NSArray *inputNodes = [bodyNode findChildTags:@"input"];

for (HTMLNode *inputNode in inputNodes) {

if ([[inputNode getAttributeNamed:@"name"] isEqualToString:@"input2"]) {

NSLog(@"%@",[inputNode getAttributeNamed:@"value"]); //Answer to first question

}

}

NSArray *spanNodes = [bodyNode findChildTags:@"span"];

for (HTMLNode *spanNode in spanNodes) {

if ([[spanNode getAttributeNamed:@"class"] isEqualToString:@"spantext"]) {

NSLog(@"%@",[spanNode allContents]); //Answer to second question

}

}

[parser release];

 类似资料: