/*
* get_xpath.c - get xpath from xml file
*
* Date: 14-Mar-2012
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <libxml/xmlschemas.h>
#include <libxml/xmlstring.h>
/*----------------------------------------------------------------------------
* Static function forward declarations
*----------------------------------------------------------------------------*/
static int parseFile(const char *filename);
static int parseNode(xmlNodePtr node);
/*----------------------------------------------------------------------------
* main
*----------------------------------------------------------------------------*/
int main(int argc, char **argv)
{
char *docname;
if (argc <= 1)
{
printf("Usage: %s docname\n", argv[0]);
return 0;
}
docname = argv[1];
if (parseFile((const char*)docname) < 0)
{
return -1;
}
return 1;
}
/*----------------------------------------------------------------------------
* Static function implementation
*----------------------------------------------------------------------------*/
static int parseFile(const char *filename)
{
xmlDocPtr doc;
/* be aware that areas of whitespace between elements are also nodes */
xmlKeepBlanksDefault(0);
doc = xmlParseFile(filename);
if (doc == NULL )
{
return -1;
}
if (parseNode(xmlDocGetRootElement(doc)) < 0)
{
xmlFreeDoc(doc);
return -1;
}
xmlFreeDoc(doc);
return 0;
}
static int parseNode(xmlNodePtr node)
{
xmlAttrPtr attr;
xmlNodePtr cur;
xmlChar *xpath;
if (!node) return -1;
/* attribute node */
for (attr = node->properties; attr; attr = attr->next)
{
xpath = xmlGetNodePath((xmlNodePtr)attr);
if (!xpath)
{
return -1;
}
fprintf(stdout, "%s\n", xpath);
fflush(stdout);
xmlFree(xpath);
}
/* empty leaf node */
if (!node->children)
{
if (node->type == XML_ELEMENT_NODE)
{
xpath = xmlGetNodePath(node);
if (!xpath)
{
return -1;
}
fprintf(stdout, "%s\n", xpath);
fflush(stdout);
xmlFree(xpath);
}
return 0;
}
/* unempty leaf node */
for (cur = node->children; cur; cur = cur->next)
{
switch(cur->type)
{
case XML_ELEMENT_NODE:
{
if (parseNode(cur) < 0)
{
return -1;
}
}
break;
case XML_TEXT_NODE:
{
xpath = xmlGetNodePath(cur->parent);
if (!xpath)
{
return -1;
}
fprintf(stdout, "%s\n", xpath);
fflush(stdout);
xmlFree(xpath);
}
break;
default:
break;
}
}
return 0;
}
get_xpath
最新推荐文章于 2022-11-08 21:29:50 发布