2010-06-11 26 views
9

Xin vui lòng ai đó có thể chỉ cho tôi một ví dụ đơn giản về phân tích cú pháp một số HTML bằng cách sử dụng libxml.Ví dụ phân tích HTML libxml2 đơn giản, sử dụng Objective-c, Xcode và HTMLparser.h

#import <libxml2/libxml/HTMLparser.h> 

NSString *html = @"<ul>" 
    "<li><input type=\"image\" name=\"input1\" value=\"string1value\" /></li>" 
    "<li><input type=\"image\" name=\"input2\" value=\"string2value\" /></li>" 
    "</ul>" 
    "<span class=\"spantext\"><b>Hello World 1</b></span>" 
    "<span class=\"spantext\"><b>Hello World 2</b></span>"; 

1) Giả sử tôi muốn phân tích giá trị của đầu vào có tên = input2.

Nên xuất "string2value".

2) Giả sử tôi muốn phân tích nội dung bên trong của mỗi thẻ span có class = spantext.

Nên xuất: "Hello World 1" và "Hello World 2".

+0

libxml dùng để phân tích cú pháp xml và bạn cần xem TouchXML. –

+0

Mặc dù tôi đang sử dụng HTMLparser.h? Tôi sẽ xem xét cảm ơn TouchXML. – StuR

+2

@Ayaz: libxml2 hỗ trợ phân tích HTML4. Từ tài liệu thưa thớt của TouchXML, có vẻ như nó không, vì vậy nó không thích hợp trong trường hợp này. – JeremyP

Trả lời

19

Tôi đã từng Ben Reeves' HTML Parser để đạt được những gì tôi muốn:

NSError *error = nil; 
NSString *html = 
    @"<ul>" 
     "<li><input type='image' name='input1' value='string1value' /></li>" 
     "<li><input type='image' name='input2' value='string2value' /></li>" 
    "</ul>" 
    "<span class='spantext'><b>Hello World 1</b></span>" 
    "<span class='spantext'><b>Hello World 2</b></span>"; 
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]; 
+0

Tôi biết điều này là cũ, nhưng tôi khá chắc chắn ông muốn "allContents" và không "rawContents" – clarky

+0

@clarky Cập nhật, cảm ơn. – StuR

+0

@StuR làm thư viện của mình có hoạt động cho iphone io6 phát triển không? – Dejell

1

Như Vladimir nói, cho điểm thứ hai điều quan trọng là để thay thế rawContents với Contents. rawContents sẽ in nút văn bản thô hoàn chỉnh, tức là:

<span class='spantext'><b>Hello World 1</b></span> 
Các vấn đề liên quan