我看了一些libxml2的代码示例,但是不知道如何将它们拼接起来。
使用libxml2解析或从XML文件中提取数据需要哪些步骤?
我想获取某些属性的信息,并可能对其进行存储。这应该怎么做?
libxml2提供了各种示例,展示了基本用法。
http://xmlsoft.org/examples/index.html
对于您所述的目标,tree1.c可能是最相关的。
tree1.c:遍历树以打印元素名称
解析文件到树中,使用 xmlDocGetRootElement() 获取根元素,然后遍历文档并按文档顺序打印所有元素名称。
http://xmlsoft.org/examples/tree1.c
一旦您拥有一个元素的xmlNode结构体,"properties"成员就是属性的链接列表。每个xmlAttr对象都有一个"name"和"children"对象(分别是该属性的名称/值),以及一个"next"成员,指向下一个属性(或空值为最后一个属性)。
在这里,我提到了从Windows平台上的文件中提取XML/HTML数据的完整过程。
Also download its dependency iconv.dll and zlib1.dll from the same page
Extract all .zip files into the same directory. For Ex: D:\demo\
Copy iconv.dll, zlib1.dll and libxml2.dll into c:\windows\system32 deirectory
Make libxml_test.cpp file and copy following code into that file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/HTMLparser.h>
void traverse_dom_trees(xmlNode * a_node)
{
xmlNode *cur_node = NULL;
if(NULL == a_node)
{
//printf("Invalid argument a_node %p\n", a_node);
return;
}
for (cur_node = a_node; cur_node; cur_node = cur_node->next)
{
if (cur_node->type == XML_ELEMENT_NODE)
{
/* Check for if current node should be exclude or not */
printf("Node type: Text, name: %s\n", cur_node->name);
}
else if(cur_node->type == XML_TEXT_NODE)
{
/* Process here text node, It is available in cpStr :TODO: */
printf("node type: Text, node content: %s, content length %d\n", (char *)cur_node->content, strlen((char *)cur_node->content));
}
traverse_dom_trees(cur_node->children);
}
}
int main(int argc, char **argv)
{
htmlDocPtr doc;
xmlNode *roo_element = NULL;
if (argc != 2)
{
printf("\nInvalid argument\n");
return(1);
}
/* Macro to check API for match with the DLL we are using */
LIBXML_TEST_VERSION
doc = htmlReadFile(argv[1], NULL, HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING | HTML_PARSE_NONET);
if (doc == NULL)
{
fprintf(stderr, "Document not parsed successfully.\n");
return 0;
}
roo_element = xmlDocGetRootElement(doc);
if (roo_element == NULL)
{
fprintf(stderr, "empty document\n");
xmlFreeDoc(doc);
return 0;
}
printf("Root Node is %s\n", roo_element->name);
traverse_dom_trees(roo_element);
xmlFreeDoc(doc); // free document
xmlCleanupParser(); // Free globals
return 0;
}
Open Visual Studio Command Promt
Go To D:\demo directory
execute cl libxml_test.cpp /I".\libxml2-2.7.8.win32\include" /I".\iconv-1.9.2.win32\include" /link libxml2-2.7.8.win32\lib\libxml2.lib command
Run binary using libxml_test.exe test.html command(Here test.html may be any valid HTML file)
xmlGetProp
函数的文档,以获取节点属性的值,例如<node property="value"/>
。 - James Morris