1
我在深入解析xml文件時遇到了問題。爲了簡單起見,我們假設我有這樣的XML文件結構,在xmlsoft.org提供:如何更深入地使用libxml2解析xml文件
<?xml version="1.0"?>
<story>
<storyinfo>
<author>John Fleck</author>
<datewritten>June 2, 2002</datewritten>
<keyword>example keyword</keyword>
</storyinfo>
<body>
<headline>This is the headline</headline>
<para>This is the body text.</para>
</body>
</story>
爲了檢索XML的一致好評文件中的每個關鍵字,開發商的目的此解決方案:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
void
parseStory (xmlDocPtr doc, xmlNodePtr cur) {
xmlChar *key;
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"keyword"))) {
key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
printf("keyword: %s\n", key);
xmlFree(key);
}
cur = cur->next;
}
return;
}
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 *) "story")) {
fprintf(stderr,"document of the wrong type, root node != story");
xmlFreeDoc(doc);
return;
}
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo"))){
parseStory (doc, cur);
}
cur = cur->next;
}
xmlFreeDoc(doc);
return;
}
int
main(int argc, char **argv) {
char *docname;
if (argc <= 1) {
printf("Usage: %s docname\n", argv[0]);
return(0);
}
docname = argv[1];
parseDoc (docname);
return (1);
}
我的疑問是:如果,例如,<storyinfo>
有另外的屬性一樣
<storyinfo>
...
<rev>
<id> 26546 </id>
</rev>
</storyinfo>
我怎麼能訪問/的printf(EG)<id>
從<rev>
?底線,再一次,我怎麼能越來越深入得到我想要的?對於上面的例子,我試過了,沒有成功:
之前xmlFreeDoc釋放(DOC)行parseDoc功能添加此
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"rev"))){
parseRev (doc, cur);
}
cur = cur->next;
}
創建一個新的功能,parseRev(xmlDocPtr DOC,的xmlNodePtr CUR):
void
parseRev (xmlDocPtr doc, xmlNodePtr cur) {
xmlChar *key;
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"id"))) {
key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
printf("id: %s\n", key);
xmlFree(key);
}
cur = cur->next;
}
return;
}
我該如何做到這一點?
只需使用'storyinfo'節點從'parseStory'調用'parseRev'即可。 – nwellnhof