
xml_set_element_handler 함수는 XML 문서를 파싱하는 동안 특정 태그를 인식할 수 있도록 도와주는 함수입니다.
이 함수를 사용하기 위해서는 두 개의 콜백 함수를 등록해야 합니다.
1. 첫 번째 콜백 함수는 시작 태그를 인식할 때 호출되는 함수입니다.
#hostingforum.kr
c
void start_element_handler(void *userData, const xmlChar *name, const xmlChar atts)
이 함수의 파라미터는 userData(사용자 데이터), name(태그 이름), atts(태그 속성)입니다.
예를 들어, "name" 태그를 인식할 때 호출되는 함수는 다음과 같습니다.
#hostingforum.kr
c
void start_element_handler(void *userData, const xmlChar *name, const xmlChar atts) {
if (xmlStrcmp(name, (const xmlChar *)"name") == 0) {
// "name" 태그가 인식되었을 때 호출되는 코드
}
}
2. 두 번째 콜백 함수는 종료 태그를 인식할 때 호출되는 함수입니다.
#hostingforum.kr
c
void end_element_handler(void *userData, const xmlChar *name)
이 함수의 파라미터는 userData(사용자 데이터), name(태그 이름)입니다.
예를 들어, "name" 태그를 인식할 때 호출되는 함수는 다음과 같습니다.
#hostingforum.kr
c
void end_element_handler(void *userData, const xmlChar *name) {
if (xmlStrcmp(name, (const xmlChar *)"name") == 0) {
// "name" 태그가 종료되었을 때 호출되는 코드
}
}
xml_set_element_handler 함수를 사용하여 태그를 인식하고, 태그 내 텍스트를 추출하는 방법은 다음과 같습니다.
#hostingforum.kr
c
#include
#include
int main() {
xmlDocPtr doc;
xmlNodePtr root;
xmlNodePtr cur;
xmlChar *name;
// XML 문서를 파싱하는 코드
doc = xmlParseFile("example.xml");
root = xmlDocGetRootElement(doc);
xmlSetGenericElementHandler(start_element_handler, end_element_handler, NULL, NULL);
for (cur = root->children; cur != NULL; cur = cur->next) {
if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->name, (const xmlChar *)"name") == 0) {
name = xmlNodeGetContent(cur);
printf("%sn", name);
xmlFree(name);
}
}
xmlFreeDoc(doc);
return 0;
}
이 코드는 "example.xml" 파일을 파싱하고, "name" 태그 내 텍스트를 추출하여 화면에 출력합니다.
이 방법을 사용하여 XML 문서를 파싱하고, 특정 태그를 인식하여 태그 내 텍스트를 추출할 수 있습니다.
2025-04-26 23:29