libxml2库函数添加子节点不能保存和不能换行以及读取子节点数不对的解决方法

来源:互联网 发布:淘宝买家退款率从哪看 编辑:程序博客网 时间:2024/06/07 09:54

1、添加子节点无法保存成功?

  原因:代码中的根节点与解析过后的doc不是配套的,属程序编写过程的错误。

  解决方法: 把两者对应起来,再进行添加保存就好。


2、添加过程中无法换行?

通过查找资料,发现在xmlSaveFormatFile(xmlFileName,doc,1);代码之前需要增加两行代码。


xmlKeepBlanksDefault(0) ;//libxml2 global variable .

 xmlIndentTreeOutput = 1 ;// indent .with \n 


3、读取的子节点数不对?

原因:之前我是用doc = xmlParseFile(xmlFileName); 来解析文件的,发现一直有问题,

           后来换成  doc = xmlReadFile(xmlFileName,"GB2312",XML_PARSE_NOBLANKS);后,问题解决。

查看libxml2库中的说明,其说前者:

Function: xmlParseFile

xmlDocPtrxmlParseFile(const char * filename)

parse an XML file and build a tree. Automatic support for ZLIB/Compress compressed document is provided by default if found at compile-time.

filename:the filenameReturns:the resulting document tree if the file was wellformed, NULL otherwise.
后者:(解析来自系统和网络,且多了个options参数,该参数选择XML_PARSE_NOBLANKS表现去除空节点)

Function: xmlReadFile

xmlDocPtrxmlReadFile(const char * filename,  const char * encoding,  int options)

parse an XML file from the filesystem or the network.

filename:a file or URLencoding:the document encoding, or NULLoptions:a combination of xmlParserOptionReturns:the resulting document tree

总结:不懂的东西,最好是查一下libxml2 的doc说明。

0 0