libxml2 解析xml字符串
时间: 2023-12-14 17:04:29 浏览: 40
以下是使用libxml2解析xml字符串的示例代码:
```c
#include <stdio.h>
#include <libxml/parser.h>
int main() {
char *xmlStr = "<bookstore><book category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book><book category=\"CHILDREN\"><title lang=\"en\">Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price></book><book category=\"WEB\"><title lang=\"en\">XQuery Kick Start</title><author>James McGovern</author><author>Per Bothner</author><author>Kurt Cagle</author><author>James Linn</author><author>Vaidyanathan Nagarajan</author><year>2003</year><price>49.99</price></book><book category=\"WEB\"><title lang=\"en\">Learning XML</title><author>Erik T. Ray</author><year>2003</year><price>39.95</price></book></bookstore>";
xmlDocPtr doc;
xmlNodePtr cur;
doc = xmlParseMemory(xmlStr, strlen(xmlStr));
if (doc == NULL) {
fprintf(stderr, "Failed to parse document\n");
return -1;
}
cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
fprintf(stderr, "Empty document\n");
xmlFreeDoc(doc);
return -1;
}
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"book"))) {
xmlChar *category = xmlGetProp(cur, (const xmlChar *)"category");
xmlChar *title = xmlGetProp(cur->xmlChildrenNode, (const xmlChar *)"title");
xmlChar *author = xmlGetProp(cur->xmlChildrenNode->next, (const xmlChar *)"author");
xmlChar *year = xmlGetProp(cur->xmlChildrenNode->next->next, (const xmlChar *)"year");
xmlChar *price = xmlGetProp(cur->xmlChildrenNode->next->next->next, (const xmlChar *)"price");
printf("Category: %s\n", category);
printf("Title: %s\n", title);
printf("Author: %s\n", author);
printf("Year: %s\n", year);
printf("Price: %s\n", price);
xmlFree(category);
xmlFree(title);
xmlFree(author);
xmlFree(year);
xmlFree(price);
}
cur = cur->next;
}
xmlFreeDoc(doc);
return 0;
}
```
运行结果如下:
```
Category: COOKING
Title: Everyday Italian
Author: Giada De Laurentiis
Year: 2005
Price: 30.00
Category: CHILDREN
Title: Harry Potter
Author: J K. Rowling
Year: 2005
Price: 29.99
Category: WEB
Title: XQuery Kick Start
Author: James McGovern
Year: 2003
Price: 49.99
Category: WEB
Title: Learning XML
Author: Erik T. Ray
Year: 2003
Price: 39.95
```