我刚开始使用 libxml 来解析 xml。我只需要知道根节点“beatles”是否存在,然后获取子子节点“lastname”。我的代码如下
#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;
printf ( "Here\n" );
while ( cur != NULL )
{
if ( ( !xmlStrcmp ( cur -> name, ( const xmlChar * ) "lastname" ) ) )
{
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;
}
printf ( "Parsing Successful\n" );
cur = xmlDocGetRootElement ( doc );
if ( cur == NULL )
{
fprintf ( stderr, "empty document \n" );
xmlFreeDoc ( doc );
return;
}
printf ( "Got the root Node\n" );
if ( xmlStrcmp ( cur->name, ( const xmlChar * ) "beatles" ) )
{
fprintf ( stderr, "Document of the wrong type root node != ");
xmlFreeDoc(doc);
return;
}
printf ( "Got the root \n" );
cur = cur -> xmlChildrenNode;
while ( cur != NULL )
{
if ( !(xmlStrcmp ( cur->name, ( const xmlChar * ) "name" ) ) )
{
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 );
}
xml文件是
<?xml version="1.0"?>
<beatles>
<beatle link="http://www.paulmccartney.com">
<name>
<firstname>Paul</firstname>
<lastname>McCartney</lastname>
</name>
</beatle>
我能够获得根节点“披头士”,但找不到“名称”和“姓氏”。请帮我解决一下这个。
如果还有其他 libxml 函数可以使用,请告诉我。谢谢。