2012-03-19 4 views
3

같은 태그 데이터의 조기 종료로방법 C의 프로그래밍

내가 그것을 어떻게 할 수있는 더러운 아마 HTML 더러운 HTML을 구문 분석 libxml2를 사용 하는가? 감사합니다

답변

9

libxml2 HTML 파서를 사용하면 "더티"HTML을 정규화 된 트리로 정규화합니다. 는

+0

오 ~ 유용합니다. 대단히 감사합니다.^_^ –

+0

^^^ upvote 버튼이 바로 있습니다;) –

4

http://xmlsoft.org/html/libxml-HTMLparser.htmlhtmlDocPtr htmlParseFile(const char * filename, const char * encoding) 내가 인해 지식의 부족으로 너무 많은 문제에 직면 참조하십시오. 그래서 전체 데모 프로그램을 작성하여 libxml2 라이브러리를 사용하여 HTML을 구문 분석합니다.

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <libxml/HTMLparser.h> 

void traverse_dom_trees(xmlNode * a_node) 
{ 
    xmlNode *cur_node = NULL; 

    if(NULL == a_node) 
    { 
     //printf("Invalid argument a_node %p\n", a_node); 
     return; 
    } 

    for (cur_node = a_node; cur_node; cur_node = cur_node->next) 
    { 
     if (cur_node->type == XML_ELEMENT_NODE) 
     { 
      /* Check for if current node should be exclude or not */ 
      printf("Node type: Text, name: %s\n", cur_node->name); 
     } 
     else if(cur_node->type == XML_TEXT_NODE) 
     { 
      /* Process here text node, It is available in cpStr :TODO: */ 
      printf("node type: Text, node content: %s, content length %d\n", (char *)cur_node->content, strlen((char *)cur_node->content)); 
     } 
     traverse_dom_trees(cur_node->children); 
    } 
} 

int main(int argc, char **argv) 
{ 
    htmlDocPtr doc; 
    xmlNode *roo_element = NULL; 

    if (argc != 2) 
    { 
     printf("\nInvalid argument\n"); 
     return(1); 
    } 

    /* Macro to check API for match with the DLL we are using */ 
    LIBXML_TEST_VERSION  

    doc = htmlReadFile(argv[1], NULL, HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING | HTML_PARSE_NONET); 
    if (doc == NULL) 
    { 
     fprintf(stderr, "Document not parsed successfully.\n"); 
     return 0; 
    } 

    roo_element = xmlDocGetRootElement(doc); 

    if (roo_element == NULL) 
    { 
     fprintf(stderr, "empty document\n"); 
     xmlFreeDoc(doc); 
     return 0; 
    } 

    printf("Root Node is %s\n", roo_element->name); 
    traverse_dom_trees(roo_element); 

    xmlFreeDoc(doc);  // free document 
    xmlCleanupParser(); // Free globals 
    return 0; 
} 
+0

또한 libxml2-2.7.8.win32를 사용했다는 사실을 사용자에게 알리고 싶습니다. –

관련 문제