Libxml2使用指南

简谈libxml2库函数的使用 目录前言一、XML简介1.1 什么是XML1.2 XML 和 HTML 之间的差异1.3 浅谈个人对XML的理解二、libxml2简介三、libxml2库的安装四、libxml2中主要数据结构和常用函数4.1 主要数据结构4.2 常用函数总结 前言 在做4G拨号的时候,遇到从.xml文件获取数据的部分。所以趁机简单在菜鸟教程学习了xml。在使用libxml2库的时候,我们有必要先了解一下xml的语法规则。在了解xml的时候顺带又把HTML过了一下。 提示:以下是本篇文章正文内容,下面案例可供 阅读详情

Libxml2使用指南

一、Libxml2介绍:

Libxml2 是一个xml的c语言版的解析器,本来是为Gnome项目开发的工具,是一个基于MIT License的免费开源软件。它除了支持c语言版以外,还支持c++、PHP、Pascal、Ruby、Tcl等语言的绑定,能在Windows、Linux、Solaris、MacOsX等平台上运行。功能还是相当强大的,相信满足一般用户需求没有任何问题。

二、Libxml2安装:

一般如果在安装系统的时候选中了所有开发库和开发工具的话(Fedora Core系列下),应该不用安装,下面介绍一下手动安装:
    1) 从xmlsoft站点或ftp(ftp.xmlsoft.org)站点下载libxml压缩包(libxml2-xxxx.tar.gz)
    2) 对压缩包进行解压缩
    tar xvzf libxml2-xxxx.tar.gz
    3) 进入解压缩后的文件夹中运行

./configure

Make

make install

安装完成后就可以使用简单的代码解析XML文件,包括本地和远程的文件,但是在编码上有一些问题。Libxml默认只支持 UTF-8的编码,无论输入输出都是UTF-8,所以如果你解析完一个XML得到的结果都是UTF-8的,如果需要输出GB2312或者其它编码,需要 ICONV来做转码(生成UTF-8编码的文件也可以用它做),如果系统中没有安装iconv的话,需要安装libiconv。

1) 下载libiconv压缩包(例如libiconv-1.11.tar.gz)

2) 对压缩包进行解压缩

tar xvzf libiconv-1.11.tar.gz

3) 进入解压缩后的文件夹中运行

./configure

Make

make install


三、关于XML:

在开始研究 Libxml2 库之前,先了解一下XML的相关基础。XML 是一种基于文本的格式,它可用来创建能够通过各种语言和平台访问的结构化数据。它包括一系列类似 HTML 的标记,并以树型结构来对这些标记进行排列。

例如,可参见清单 1 中介绍的简单文档。为了更清楚地显示 XML 的一般概念,下面是一个简化的XML文件。

清单 1. 一个简单的 XML 文件

<?xml version="1.0" encoding="UTF-8"?>

<files>

<owner>root</owner>

<action>delete</action>

<age units="days">10</age>

</files>

 

清单 1 中的第一行是 XML 声明,它告诉负责处理 XML 的应用程序,即解析器,将要处理的 XML 的版本。大部分的文件使用版本 1.0 编写,但也有少量的版本 1.1 的文件。它还定义了所使用的编码。大部分文件使用 UTF-8,但是,XML 设计用来集成各种语言中的数据,包括那些不使用英语字母的语言。

接下来出现的是元素。一个元素以开始标记 开始(如 <files>),并以结束标记 结束(如 </files>),其中使用斜线 (/) 来区别于开始标记。元素是 Node 的一种类型。XML 文档对象模型 (DOM) 定义了几种不同的 Nodes 类型,包括:

Elements(如 files 或者 age)

Attributes(如 units)

Text(如 root 或者 10)

 

元素可以具有子节点。例如,age 元素有一个子元素,即文本节点 10。

 

XML 解析器可以利用这种父子结构来遍历文档,甚至修改文档的结构或内容。LibXML2 是这样的解析器中的其中一种,并且文中的示例应用程序正是使用这种结构来实现该目的。对于各种不同的环境,有许多不同的解析器和库。LibXML2 是用于 UNIX 环境的解析器和库中最好的一种,并且经过扩展,它提供了对几种脚本语言的支持,如 Perl 和 Python。

 

三、使用Libxml2

项目中要实现一个管理XML文件的后台程序,需要对XML文件进行创建,解析,修改,查找等操作,下面介绍如何利用libxml2提供的库来实现上述功能。

1、创建XML文档:

我们使用xmlNewDoc()来创建XML文档,然后使用

xmlNewNode(),xmlNewChild(),xmlNewProp(),xmlNewText()等函数向XML文件中添加节点及子节点,设置元素和属性,创建完毕后用xmlSaveFormatFileEnc()来保存XML文件到磁盘(该函数可以设置保存XML文件时的编码格式)。

示例1:

#include <stdio.h>

#include <libxml/parser.h>

#include <libxml/tree.h>

int main(int argc, char **argv)

{

xmlDocPtr doc = NULL;

xmlNodePtr root_node = NULL, node = NULL, node1 = NULL;

 

// Creates a new document, a node and set it as a root node

doc = xmlNewDoc(BAD_CAST "1.0");

root_node = xmlNewNode(NULL, BAD_CAST "root");

xmlDocSetRootElement(doc, root_node);

 

//creates a new node, which is "attached" as child node of root_node node.

xmlNewChild(root_node, NULL, BAD_CAST "node1",BAD_CAST "content of node1");

 

// xmlNewProp() creates attributes, which is "attached" to an node.

node=xmlNewChild(root_node, NULL, BAD_CAST "node3", BAD_CAST"node has attributes");

xmlNewProp(node, BAD_CAST "attribute", BAD_CAST "yes");

//Here goes another way to create nodes.

node = xmlNewNode(NULL, BAD_CAST "node4");

node1 = xmlNewText(BAD_CAST"other way to create content");

xmlAddChild(node, node1);

xmlAddChild(root_node, node);

 

//Dumping document to stdio or file

xmlSaveFormatFileEnc(argc > 1 ? argv[1] : "-", doc, "UTF-8", 1);

xmlFreeDoc(doc);

xmlCleanupParser();

xmlMemoryDump();//debug memory for regression tests

 

return(0);

}

2、解析XML文档

解析文档时仅仅需要文件名并只调用一个函数,并有错误检查,常用的相关函数有 xmlParseFile(),xmlParseDoc(),获取文档指针后,就可以使用xmlDocGetRootElement()来获取根元素节点指针,利用该指针就可以在DOM树里漫游了,结束后要调用xmlFreeDoc()释放。

例2:

 

xmlDocPtr doc; //定义解析文档指针

xmlNodePtr cur; //定义结点指针(你需要它为了在各个结点间移动)

xmlChar *key;

doc = xmlReadFile(url, MY_ENCODING, 256); //解析文件

 

if (doc == NULL ) {

fprintf(stderr,"Document not parsed successfully. /n");

return;

}

 

cur = xmlDocGetRootElement(doc); //确定文档根元素

 

if (cur == NULL) {

fprintf(stderr,"empty document/n");

xmlFreeDoc(doc);

return;

}

 

if (xmlStrcmp(cur->name, (const xmlChar *) "root")) {

fprintf(stderr,"document of the wrong type, root node != root");

xmlFreeDoc(doc);

return;

}

 

cur = cur->xmlChildrenNode;

while(cur!=NULL) {

if ((!xmlStrcmp(cur->name, (const xmlChar *)"keyword"))) {

key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);

printf("keyword: %s/n", key);

xmlFree(key);

}

 

cur = cur->next;

}

xmlFreeDoc(doc);

 

3、修改XML元素及属性等信息

要修改XML文档里的元素及属性等信息,先需要解析XML文档,获得一个节点指针(xmlNodePtr node),利用该节点指针漫游DOM树,就可以在XML文档中获取,修改,添加相关信息。

示例3:

得到一个节点的内容:

xmlChar *value = xmlNodeGetContent(node);

返回值value应该使用xmlFree(value)释放内存

得到一个节点的某属性值:

xmlChar *value = xmlGetProp(node, (const xmlChar *)"prop1");

返回值需要xmlFree(value)释放内存

 

设置一个节点的内容:

xmlNodeSetContent(node, (const xmlChar *)"test");

设置一个节点的某属性值:

xmlSetProp(node, (const xmlChar *)"prop1", (const xmlChar *)"v1");

添加一个节点元素:

xmlNewTextChild(node, NULL, (const xmlChar *)"keyword", (const xmlChar *)"test Element");

添加一个节点属性:

xmlNewProp(node, (const xmlChar *)"prop1", (const xmlChar *)"test Prop");

4、查找XML节点

有时候对一个XML文档我们可能只关心其中某一个或某几个特定的Element的值或其属性,如果漫游DOM树将是很痛苦也很无聊的事,利用XPath可以非常方便地得到你想的Element。下面是一个自定义函数:

示例4:

xmlXPathObjectPtr get_nodeset(xmlDocPtr doc, const xmlChar *xpath) {

xmlXPathContextPtr context;

xmlXPathObjectPtr result;

context = xmlXPathNewContext(doc);

if (context == NULL) {

printf("context is NULL/n");

return NULL;

}

result = xmlXPathexpression_r(xpath, context);

xmlXPathFreeContext(context);

if (result == NULL) {

printf("xmlXPathExpression return NULL/n");

return NULL;

}

if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {

xmlXPathFreeObject(result);

printf("nodeset is empty/n");

return NULL;

}

return result;

}

在doc指向的XML文档中查询满足xpath表达式条件的节点,返回满足这一条件的节点集合查询条件xpath的写法参见xpath相关资料。在查询完毕获取结果集后,就可以通过返回的 xmlXPathObjectPtr 结构访问该节点:

示例5:

xmlChar *xpath = ("/root/node/[@key='keyword']");

xmlXPathObjectPtr app_result = get_nodeset(doc,xpath);

if (app_result == NULL) {

printf("app_result is NULL/n");

return;

}

 

int i = 0;

xmlChar *value;

 

if(app_result) {

xmlNodeSetPtr nodeset = app_result->nodesetval;

for (i=0; i < nodeset->nodeNr; i++) {

cur = nodeset->nodeTab[i];

cur = cur->xmlChildrenNode;

 

while(cur!=NULL) {

value = xmlGetProp(cur,(const xmlChar *)"key");

if (value != NULL) {

printf("value: %s/n/n", d_ConvertCharset("utf-8", "GBK", (char *)value));

xmlFree(value);

}

value = xmlNodeGetContent(cur);

if (value != NULL) {

printf("value: %s/n/n", d_ConvertCharset("utf-8", "GBK", (char *)value));

xmlFree(value);

}

}

}

xmlXPathFreeObject (app_result);

}

通过get_nodeset()返回的结果集,我们可以获取该节点的元素及属性,也可以修改该节点的值。示例中在获取值打印的时候用到 d_ConvertCharset()函数来改变编码格式为GBK,以方便正确读取可能的中文字符。

 

5、编码问题

由于Libxml一般以UTF-8格式保存和操纵数据,如果你的程序使用其它的数据格式,比如中文字符(GB2312,GBK编码),就必须使用Libxml函数转换到UTF-8。如果你想你的程序以除UTF-8外的其它编码方式输出也必须做转换。

下面的示例程序提供几个函数来实现对数据编码格式的转换,其中有的要用到Libiconv,因此为了确保他们能正常工作,先检查以下系统中是否已经安装libiconv库。

示例6:

xmlChar *ConvertInput(const char *in, const char *encoding) {

unsigned char *out;

int ret;

int size;

int out_size;

 

int temp;

xmlCharEncodingHandlerPtr handler;

 

if (in == 0)

return 0;

 

handler = xmlFindCharEncodingHandler(encoding);

 

if (!handler) {

printf("ConvertInput: no encoding handler found for '%s'/n", encoding ? encoding : "");

return 0;

}

 

size = (int) strlen(in) + 1;

out_size = size * 2 - 1;

 

out = (unsigned char *) xmlMalloc((size_t) out_size);

if (out != 0) {

temp = size - 1;

ret = handler->input(out, &out_size, (const unsigned char *) in, &temp);

if ((ret < 0) || (temp - size + 1)) {

if (ret < 0) {

printf("ConvertInput: conversion wasn't successful./n");

} else {

printf("ConvertInput:conversion wasn't successful. converted: %i octets./n", temp);

}

xmlFree(out);

out = 0;

} else {

out = (unsigned char *) xmlRealloc(out, out_size + 1);

out[out_size] = 0;

}

} else {printf("ConvertInput: no mem/n");}

return out;

}

 

 

示例7:

char * Convert( char *encFrom, char *encTo, const char * in) {

static char bufin[1024], bufout[1024], *sin, *sout;

int mode, lenin, lenout, ret, nline;

iconv_t c_pt;

 

if ((c_pt = iconv_open(encTo, encFrom)) == (iconv_t)-1) {

printf("iconv_open false: %s ==> %s/n", encFrom, encTo);

return NULL;

}

iconv(c_pt, NULL, NULL, NULL, NULL);

 

lenin = strlen(in) + 1;

lenout = 1024;

sin = (char *)in;

sout = bufout;

 

ret = iconv(c_pt, &sin, (size_t *)&lenin, &sout, (size_t *)&lenout);

if (ret == -1) {

return NULL;

}

 

iconv_close(c_pt);

return bufout;

}

 

 

 

示例8:

char *d_ConvertCharset(char *cpEncodeFrom, char *cpEncodeTo, const char *cpInput) {

static char s_strBufOut[1024], *sin, *cpOut;

size_t iInputLen, iOutLen, iReturn;

 

iconv_t c_pt;

if ((c_pt = iconv_open(cpEncodeTo, cpEncodeFrom)) == (iconv_t)-1) {

printf("iconv_open failed!/n");

return NULL;

}

iconv(c_pt, NULL, NULL, NULL, NULL);

iInputLen = strlen(cpInput) + 1;

iOutLen = 1024;

sin = (char *)cpInput;

cpOut = s_strBufOut;

iReturn = iconv(c_pt, &sin, &iInputLen, &cpOut, &iOutLen);

if (iReturn == -1) {

return NULL;

}

iconv_close(c_pt);

return s_strBufOut;

}

 

通过上述函数,可以方便的在XML文件中保存并操纵中文字符。

利用libxml2解析xml文件 简单介绍libxml2的安装及基于C语言从xml文件中解析出相关内容。 阅读详情

相关推荐

Linux如何安装并配置libxml2库?解决“libxml2 not found“问题

这里写目录标题libxml2库方法比较Opt1:包管理器安装Debian/UbuntuCentOSOpt2:编译安装1. 下载源码2. 编译安装3. 环境变量卸载libxml2 libxml2库 libxml是一个用来解析XML文档的函数库。 它用C语言写成,并且能为多种语言所调用,例如:C语言,C++、XSH、C#,、Python、Kylix/Delphi、Ruby和PHP等。 它最初是为GNOME开发的项目,但现在可以用在各种各样的方面。libXML代码可移植性非常好,因为它基于标准的ANSI C库,并

Mintimate的优快云博客 3万+

libxml2 - 高性能的XML解析库

libxml2是一个开源的、高性能的XML解析库,它提供了丰富的API接口,支持XML文档的读取、创建、修改和查询等功能。 ## 项目简介 libxml2最初由 GNOME 项目开发,并且已经成为许多开源项目的核心组件,如 GNOME、X.org 和 GTK+ 等。它的目标是提供一个高效、稳定并且易于使用的XML处理库,支持各种XML相关的标准和技术,包括 XPath、XSLT、XML Sch

gitblog_00008的博客 1500

libxml2在mingw中的使用

<br />libxml2是一套非常好用的xml库,官网是http://www.libxml.org/,但是天知道是什么原因,此网页无法访问。<br /> <br />好不容易下载下来,在mingw中却问题多多。<br />第一个问题:<br /> <br />E:**:14: undefined reference to `_imp__xmlFree' E:**:48: undefined reference to `_imp__xmlFree' E:**:14: undefined referenc

2552

C的xml编程-libxml2

<br />  这里主要讲述libxml2在linux下的使用。<br />(以下内容除了linux下的安装步骤是自己写的,其余均出自<br />http://www.blogjava.net/wxb_nudt/archive/2007/11/28/161340.html<br />,由于该篇文章讲解的非常周详,我也没必要重写一遍了。如果该篇文章早出些时候,早期研发我也不会走非常多弯路了。虽然在该篇文章出现之前我已对libxml2较熟悉了并研发完毕,但为了备忘,目前将该篇文章作为收藏之用。在此再次感谢这篇文

河边钓鱼 2302

LIBXML2库使用指南

C++的XML编程经验――LIBXML2库使用指南 写这篇文章的原因有如下几点:1)C++标准库中没有操作XML的方法,用C++操作XML文件必须熟悉一种函数库,LIBXML2是其中一种很优秀的XML库,而且它同时支持多种编程语言;2)LIBXML2库的Tutorial写得不太好,尤其是编码转换的部分,不适用于中文编码的转换;3)网上的大多数关于Libxml2的介绍仅仅是翻译了自带的资料,没

shanzhizi的专栏 2497

libxml2 使用示例

libxml2 使用示例, readNode countNode insertNode updateNode deleteNode

libxml2使用

Libxml2使用指南 一、Libxml2介绍: Libxml2 是一个xml的c语言版的解析器,本来是为Gnome项目开发的工具,是一个基于MIT License的免费开源软件。它除了支持c语言版以外,还支持c++、PHP、Pascal、Ruby、Tcl等语言的绑定,能在Windows、Linux、Solaris、MacOsX等平台上运行。功能还是相当强大的,相信满足一般用户需求没有任何问题

lotus302的专栏 1281

OV5640调试大坑,关于binning、RES分辨率与EV曝光

OV5640在使用binning模式时,必须考虑使用场景,分辨率下降叠加动态范围压缩,会使目标对象细节在高光环境下大量丢失,2x2的binning模式,分辨率会远低于感光面积的1/4。

chongyun_的专栏 1827

Ubuntu下libxml2的安装和使用

这篇文章主要介绍libxml2的安装和使用,xml文件的主要作用就是配置文件,实际的应用在前面的章节Audio设备文件解析中有需要对audio_policy_configuration.xml文件解析,google使用的是开源库libxml2,在源码目录/external/libxml2下面,现在就单独对这个库进行分析。 在终端中执行 wang@wang:~/test$ sudo apt-

wangrl的博客 1万+

Android应用之【巧妙隐藏桌面图标的进阶方案】

本文详细探讨了Android应用中隐藏桌面图标的进阶方案,解决了传统方法在Android 10及以上版本中出现的黑色图标残留问题。通过Intent-Filter配置和厂商适配技巧,实现子应用真正隐身,同时确保主应用正常启动。适用于企业工具套件、模块化系统等场景,提升用户体验和安全性。

weixin_28363123的博客 508

从原理到调试:手把手教你用Matlab解码互补格雷码与相移码(附数据与常见错误排查)

本文详细介绍了如何使用Matlab解码互补格雷码与相移码,涵盖从原理到调试的全过程。通过实际案例和代码示例,帮助读者掌握结构光三维重建中的相位解包裹技术,并提供了常见错误排查与优化建议,提升解码效率与准确性。

weixin_29090917的博客 220

linux下libxml2库使用说明

第一章 什么是XML? 1.xml简介 XML(Extensible Markup Language)即可扩展标记语言,它与HTML一样,都是SGML(Standard Generalized Markup Language,标准通用标记语言)。Xml是Internet环境中

lanlicen的专栏 1万+

RT-Thread stm32h7使用串口DMA

stm32h7在rtthread中无法使用串口DMA,通过更改驱动代码使其支持串口DMA

qq_35141454的博客 2286

python中如何安装libxml2

按习惯使用pip install libxml2安装失败: 提示找不到叫 libxml2 的插件版本 ubuntu@VM-0-17-ubuntu:/usr/bin$ sudo pip install libxml2 WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/55

qq_27361945的博客 8972

HFSS线圈仿真避坑指南:从建模到寄生参数分析的完整流程

本文详细介绍了HFSS线圈仿真的完整流程,从精准建模到寄生参数优化,特别针对Ansys Electronics Desktop用户提供实用指南。涵盖线圈几何构建、材料属性配置、端口激励设置及寄生电阻与电感分析等关键步骤,帮助工程师避免常见错误,提升仿真精度与效率。

weixin_29209801的博客 549

05 - matlab m_map地学绘图工具基础函数 - 设置比例尺指北针

本篇介绍下m_map中添加指北针(m_northarrow)、比例尺(m_ruler)和进行比例缩放(m_scale)的函数及其用法 。提供了 示例以便参考,罗列了 各函数可设属性。希望对绘图的你有所帮助。

weixin_43339605的博客 1947

Linux下libxml2的使用

  http://www.cnblogs.com/flysnail/archive/2012/06/25/2561319.html----一、下载、安装下载libxml2,官方网站,下载合适自己版本的源码包。http://rpmfind.net/linux/rpm2html/search.php?query=libxml2-devel俺下载的版本为libxml2-devel-2.6.32...

weixin_33965305的博客 1070

使用Libxml2操作XML文档

一、Libxml2介绍: Libxml2 是一个xml的c语言版的解析器,本来是为Gnome项目开发的工具,是一个基于MIT License的免费开源软件。它除了支持c语言版以外,还支持c++、PHP、Pascal、Ruby、Tcl等语言的绑定,能在Windows、Linux、Solaris、MacOsX等平台上运行。功能还是相当强大的,相信满足一般用户需求没有任何问题。二、 Libx

armman的专栏 1万+

AUTOSAR进阶图解==>AUTOSAR_EXP_CDDDesignAndIntegrationGuideline

本文档提供了AUTOSAR架构中复杂驱动(CDD)的设计与集成指南。CDD作为非标准化的软件实体,位于复杂驱动层,实现传感器评估、执行器控制、微控制器访问等特殊功能。文档详细阐述了CDD的架构特点、设计建议(包括文档要求、文件结构、接口描述等)以及与其他模块(RTE、库、标准BSW等)的集成方式。特别强调了CDD在多核系统和MCAL层中的实现考量,为开发人员提供了从文档规范到代码实现的全方位指导,确保CDD在保持AUTOSAR兼容性的同时满足特殊功能需求。

一名留德华的,康德的信徒的,专注于汽车电子领域的博客 1889

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

libxml2

<br />  在RH8上安装PHP5时会报错:<br />  configure: error: libxml2 version 2.6.11 or greater required.<br />  这是由于libxml2版本低造成的,可以从www.xmlsoft.org下载程序包进行安装。<br />  rpm -e --nodeps libxml2 (强行卸掉)<br />  ./configure --prefix=/usr/lib /<br />        --with-ftp /<br />

tg5156的专栏 1740

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Libxml2 编译

Libxml2 是一个xml c语言版的解析器,本来是为Gnome项目开发的工具,是一个基于MIT License的免费开源软件。它除了支持c语言版以外, 还支持c++、PHP、Pascal、Ruby、Tcl等语言的绑定,能在Windows、Linux、Solaris、MacOsX等平台上运行。 Libxml2主要的优点有: 1. 安装、使用比较简单,容易入门; 2. 支持的编码格式较多,

多媒体编程、网络编程、系统编程、网络安全编程、驱动编程 1272

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

libxml2中文支持

LibXML2自身已经支持了中文编码,只是他的所有api处理的数据都是UTF-8类型的,所以只要在读入和写入数据时进行相应装换即可! 代码1是使用Linux下C API进行编码转换; 代码2因为libxml2已经融合了iconv,使用了libxml2的函数来进行编码转换。 /* compile: gcc -l/usr/include/libxml2 -lxml2 iconv.c input: test.xml <?xml version="1.0" encoding..

zhangge3663的博客 513
上一篇: ACE线程管理机制-线程的创建与管理
下一篇: 用gcc编译静态库,动态库
needle2
博客等级 码龄17年 46粉丝 16原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值