Example: book.c
#include <stdio.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
/**
* Story 要素を Parse する
*
* @param doc 読み込んだドキュメント (xmlDocPtr
* @param cur storyinfo 要素開始位置ノード (xmlNodePtr)
*/
static void parseInfo(xmlDocPtr doc, xmlNodePtr cur)
{
xmlChar *key;
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar*)"author"))) {
key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
printf("author: %s\n", key);
xmlFree(key);
}
cur = cur->next;
}
return;
}
/**
* ドキュメントを読み込んで parse する
*
* @param docname 読み込むドキュメントファイル名
*/
static void parseDoc(char *docname)
{
xmlDocPtr doc;
xmlNodePtr cur;
doc = xmlParseFile(docname);
if (doc == NULL) {
fprintf(stderr, "Document not parsed successfully.\n");
return;
}
cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
fprintf(stderr, "empty document.\n");
xmlFreeDoc(doc);
return;
}
if (xmlStrcmp(cur->name, (const xmlChar*)"books")) {
fprintf(stderr, "document of the wrong type, root node != config\n");
xmlFreeDoc(doc);
return;
}
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar*)"info"))) {
parseInfo(doc, cur);
}
cur = cur->next;
}
xmlFreeDoc(doc);
return;
}
/**
* book.c のメイン関数
*
* @param argc 引数の数
* @param argv 引数
* @retval 0 正常終了
* @retval -1 異常終了
*/
int main(int argc, char **argv)
{
char *docname;
if (argc <= 1) {
printf("Usage: %s docuname\n", argv[0]);
return -1;
}
docname = argv[1];
parseDoc(docname);
return 0;
}
Example: book.xml
<?xml version="1.0"?>
<books>
<info>
<author>Ernest Miller Hemingway</author>
<title>The Old Man and the Sea</title>
</info>
<info>
<author>Mark Twain</author>
<title>The Adventures of Tom Sawyer</title>
</info>
</books>
Example: Makefile
CC = gcc
CFLAGS = -Wall
LDFLAGS = -lxml2 -lws2_32
TARGET = \
book.exe
.SUFFIXES: .exe .c .o
.c.o:
$(CC) $(CFLAGS) -c -o $@ $<
.o.exe:
$(CC) -o $@ $< $(LDFLAGS)
default: $(TARGET)
clean:
rm -rf *.o *.exe
実行結果
> book.exe book.xml author: Ernest Miller Hemingway author: Mark Twain
0 件のコメント:
コメントを投稿