libxml2如何用于解析XML中的数据?

我查看了libxml2代码示例,我很困惑如何将它们拼凑在一起。

使用libxml2从XML文件解析或提取数据时需要执行哪些步骤?

我想抓住并可能存储某些属性的信息。 这是怎么做到的?

我相信你首先需要创建一个Parse树。 也许这篇文章可以提供帮助,请查看如何使用Libxml2解析树的部分 。

当我学习使用libxml2构建rss feed解析器时,我发现这两个资源很有用。

SAX界面教程

使用DOM树的教程 (包含属性值的代码示例)

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)。

http://xmlsoft.org/html/libxml-tree.html#xmlNode

http://xmlsoft.org/html/libxml-tree.html#xmlAttr

在这里,我提到了从Windows平台上的文件中提取XML / HTML数据的完整过程。

  1. 首先下载预编译的.dll表单http://xmlsoft.org/sources/win32/
  2. 还要从同一页面下载其依赖关系iconv.dllzlib1.dll

  3. 将所有.zip文件解压缩到同一目录中。 对于Ex:D:\ demo \

  4. iconv.dllzlib1.dlllibxml2.dll复制到c:\ windows \ system32 deirectory中

  5. 制作libxml_test.cpp文件并将以下代码复制到该文件中。

     #include  #include  #include  #include  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; } 
  6. 打开Visual Studio Command Promt

  7. 转到D:\ demo目录

  8. 执行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命令

  9. 使用libxml_test.exe test.html命令运行二进制文件(这里test.html可能是任何有效的HTML文件)