输出格式化的xml文件
上一篇我按照网上的资源写了一个创建xml文件的小程序,算让创建成功,但是在新增节点时发现格式不对,没有成xml的树状而是一行,详见我在简书的 创建xml文件系统 http://www.jianshu.com/p/36cc32096ac9。
经过分析和查阅资料简单的来说是xmlParseFile和xmlReadFile的问题,两个函数都可以实现,只是实现方法有些不同。下面简单的说下两者的区别
我之前使用的就是xmlParseFile,它的功能是
xmlParseFile是按默认的方式加载xml文件。需要注意的是如果要使用xmlParseFile加载文件,并修改保存话需要
Set and return the previous value for default blanks text nodes support. The 1.x version of the parser used an heuristic to try to detect ignorable white spaces. As a result the SAX callback was generating xmlSAX2IgnorableWhitespace() callbacks instead of characters() one, and when using the DOM output text nodes containing those blanks were not generated. The 2.x and later version will switch to the XML standard way and ignorableWhitespace() are only generated when running the parser in validating mode and when the current element doesn’t allow CDATA or mixed content. This function is provided as a way to force the standard behavior on 1.X libs and to switch back to the old mode for compatibility when running 1.X client code on 2.X . Upgrade of 1.X code should be done by using xmlIsBlankNode() commodity function to detect the “empty” nodes generated. This value also affect autogeneration of indentation when saving code if blanks sections are kept, indentation is not generated.
val: int 0 or 1
Returns: the last value for 0 for no substitution, 1 for substitution.
—http://xmlsoft.org/
根据上面的话当2.x版本时要设成1.
Note that format=1 provide node indenting only if xmlIndentTreeOutput=1
xmlReadFile不仅可以加载文件还可以加载URL。
使用xmlReadFile就不用做其他的处理,例如这次的小程序直接修改
就可以格式化输出了。
上面的两种方法都可以实现格式化输出的功能,输出的xml文件如下
虽然xmlParseFile和xmlReadFile都可以使用,但是建议还是要是用xmlReadFile。
在这[LINK]可以看下libxml2的作者是如何说的
“Use xmlReadFile, it’s the modern API for parsing”
而且
xmlReadFile比xmlParseFile更强大,xmlReadFile第三个参数提供了强大的选项
下一篇将尝试解析和修改。
还没有评论,来说两句吧...