libxml2 preserve empty tags

假装没事ソ 提交于 2019-12-02 00:07:07

问题


libxml2 (for C) is not preserving empty elements in their original form on a save. It replaces <tag></tag> with <tag/> which is technically correct but causes problems for us.

xmlDocPtr doc = xmlParseFile("myfile.xml");
xmlNodePtr root = xmlSaveFile("mynewfile.xml", doc);

I've tried playing with the various options (using xlmReadFile) but none seem to affect the output. One post here mentioned disabling tag compression but the example was for PERL and I've found no analog for C.

Is there an option to disable this behavior?


回答1:


Just found this enum in the xmlsave module documentation:

 Enum xmlSaveOption {
     XML_SAVE_FORMAT = 1 : format save output
     XML_SAVE_NO_DECL = 2 : drop the xml declaration
     XML_SAVE_NO_EMPTY = 4 : no empty tags
     XML_SAVE_NO_XHTML = 8 : disable XHTML1 specific rules
     XML_SAVE_XHTML = 16 : force XHTML1 specific rules
     XML_SAVE_AS_XML = 32 : force XML serialization on HTML doc
     XML_SAVE_AS_HTML = 64 : force HTML serialization on XML doc
     XML_SAVE_WSNONSIG = 128 : format with non-significant whitespace
 }

Maybe you can refactor your application to use this module for serialization, and play a little with these options. Specially with XML_SAVE_NO_EMPTY.




回答2:


Your code may look like this:

xmlSaveCtxt *ctxt = xmlSaveToFilename("mynewfile.xml", "UTF-8", XML_SAVE_FORMAT | XML_SAVE_NO_EMPTY);
if (!ctxt || xmlSaveDoc(ctxt, doc) < 0 || xmlSaveClose(ctxt) < 0)
  //...deal with the error


来源:https://stackoverflow.com/questions/10423839/libxml2-preserve-empty-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!