【发布时间】:2011-07-24 20:53:49
【问题描述】:
我查看了 libxml2 代码示例,不知道如何将它们拼凑在一起。
使用 libxml2 从 XML 文件中解析或提取数据需要哪些步骤?
我想获取并可能存储某些属性的信息。这是怎么做到的?
【问题讨论】:
我查看了 libxml2 代码示例,不知道如何将它们拼凑在一起。
使用 libxml2 从 XML 文件中解析或提取数据需要哪些步骤?
我想获取并可能存储某些属性的信息。这是怎么做到的?
【问题讨论】:
我相信你首先需要创建一个 Parse 树。也许这篇文章能帮上忙,看看How to Parse a Tree with Libxml2的部分。
【讨论】:
xmlGetProp 函数的文档,该函数将给出节点属性的值,即<node property="value"/>。
我在学习使用 libxml2 构建 rss 提要解析器时发现这两个资源很有帮助。
Tutorial using the DOM Tree(包括获取属性值的代码示例)
【讨论】:
libxml2 提供了显示基本用法的各种示例。
http://xmlsoft.org/examples/index.html
对于您的既定目标,tree1.c 可能最相关。
tree1.c:导航要打印的树 元素名称
将文件解析为树,使用 xmlDocGetRootElement() 获取根 元素,然后遍历文档并 打印文档中的所有元素名称 顺序。
http://xmlsoft.org/examples/tree1.c
一旦你有一个元素的 xmlNode 结构,“properties”成员就是一个属性的链接列表。每个 xmlAttr 对象都有一个“name”和“children”对象(分别是该属性的名称/值),以及一个指向下一个属性的“next”成员(或最后一个属性为 null)。
【讨论】:
在这里,我提到了在windows平台上从文件中提取XML/HTML数据的完整过程。
还要从同一页面下载其依赖项iconv.dll和zlib1.dll
将所有 .zip 文件解压缩到同一目录中。例如:D:\demo\
将iconv.dll、zlib1.dll和libxml2.dll复制到c:\windows\system32 目录
制作 libxml_test.cpp 文件并将以下代码复制到该文件中。
#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;
}
打开 Visual Studio 命令提示符
转到 D:\demo 目录
执行 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命令
使用 libxml_test.exe test.html 命令运行二进制文件(这里的 test.html 可以是任何有效的 HTML 文件)
【讨论】: