libxml2 preserve empty tags

2019-02-25 09:12发布

问题:

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


标签: libxml2