加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

libxml解析XML文档

发布时间:2020-12-16 00:32:22 所属栏目:百科 来源:网络整理
导读:目前三种最流行的开源 c/c++解析xml库:libxml、Xerces、expat,且三者都是跨平台的。 Xerces-C++ (C++版本): http://xerces.apache.org/xerces-c/index.html xerces2-j (java版本): http://xerces.apache.org/xerces2-j/ java版dom及sax方式解析示例: dom_
目前三种最流行的开源 c/c++解析xml库:libxml、Xerces、expat,且三者都是跨平台的。
Xerces-C++ (C++版本): http://xerces.apache.org/xerces-c/index.html
xerces2-j (java版本): http://xerces.apache.org/xerces2-j/
java版dom及sax方式解析示例:
dom_sax.rar

expat: http://expat.sourceforge.net/

一、libxml库下载
libxml官网: http://www.xmlsoft.org
libxml库下载: ftp://xmlsoft.org/libxml2/libxml2-git-snapshot.tar.gz
libxml文档下载: ftp://xmlsoft.org/libxml2/libxml-docs.tar.gz
二、libxml安装
#解压安装文件
[root@localhost xmllib]# tar -xzvf libxml2-git-snapshot.tar.gz
#然后cd进入解压后的目录,运行初始配置文件,也可使用 ./configure --prefix=$HOME/libxml 指定安装目录
#不指定安装目录,则默认安装在系统目录 /usr/local/include/libxml2
[root@localhost libxml2-2.8.0]# ./configure
#make编译
[root@localhost libxml2-2.8.0]# make
#make install安装
[root@localhost libxml2-2.8.0]# make install

注:libxml无论输入/输出,默认只支持UTF-8,如果需要输出GB2312或其他编码的内容,则需要iconv工具库来转码(如libiconv
(libiconv-1.11.tar.gz),安装与上同)
三、libxml示例
libxml 支持dom和sax方式解析,下面是从文档里抽取的一个示例(更多的实现,可参考API文档及sample文档):
1、story.xml

  1. <?xmlversion="1.0"?>
  2. <story>
  3. <storyinfo<author>John Fleck/author<datewritten>June 2,2002/datewritten<keyword>example keyword/keyword/storyinfo<body<headline>This is the headline/headline<para>This is the body text./para/body/story>
2、keyword.c
#include<stdio.h>
  • #include<string>
  • #include<stdlib<libxml/xmlmemory/parser>

  • void
  • parseStory(xmlDocPtr doc){

  • xmlChar*key;
  • cur=cur->xmlChildrenNode;
  • while(cur!=NULL{
  • if(!xmlStrcmp>nameconstxmlChar*)"keyword"{
  • key=xmlNodeListGetString(doc1;
  • printf("keyword: %sn";
  • xmlFree(key}
  • cur>next}
  • return}

  • static void
  • parseDoc(char*docname{

  • xmlDocPtr doc;
  • xmlNodePtr cur;

  • doc=xmlParseFile(docname;

  • {
  • fprintf(stderr"Document not parsed successfully. n";
  • return}

  • cur=xmlDocGetRootElement"empty documentn";
  • xmlFreeDoc}

  • (xmlStrcmp"story""document of the wrong type,root node != story""storyinfo"{
  • parseStory}

  • xmlFreeDoc}

  • int
  • mainintargc*argv{

  • char(argc=1{
  • printf"Usage: %s docnamen"[0](0}

  • docname=argv[1;
  • parseDoc;

  • return(1}
  • 3、编译运行
    [root@localhost txlib]# gcc keyword.c -o keyword -I/usr/local/include/libxml2 -lxml2 [root@localhost txlib]# [root@localhost txlib]# ./keyword story.xml keyword: example keyword

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读