perl - How to prevent XML::LibXML to save modified xml using self-closing tag -


the following working code reads xml file containing lots of empty elements, applies 2 changes , saves again under different name. changes empty elements <element></element> self-closing tags <element /> unwanted.
how save not using self-closing tags? or words how tell xml::libxml use empty tags? original file produced in commercial application, uses style empty elements, want sustain that.

#! /usr/bin/perl  use strict; use warnings; use xml::libxml;  $filename = 'out.xml'; $dom = xml::libxml->load_xml(location => $filename); $query = '//scalar[contains(@name, "partitionsno")]/value'; $i ($dom->findnodes($query)) { $i->removechildnodes(); $i->appendtext('16'); }  open $out, '>', 'out2.xml'; binmode $out; $dom->tofh($out); # out2.xml has self-closing tags  # used empty elements 

unfortunately, xml::libxml doesn't support libxml2's xmlsave module has flag save without empty tags.

as workaround can add empty text node empty elements:

for $node ($doc->findnodes('//*[not(node())]')) {     # note appendtext doesn't work.     $node->appendchild($doc->createtextnode('')); } 

this bit costly large documents, i'm not aware of better solution.

that said, fragments <foo></foo> , <foo/> both well-formed , semantically equivalent. xml parser or application treats such fragments differently buggy.


note people believe xml spec recommends using self-closing tags, that's not true. xml spec says:

empty-element tags may used element has no content, whether or not declared using keyword empty. interoperability, empty-element tag should used, , should used, elements declared empty.

this means elements declared empty in dtd. other elements, or if no dtd present, xml standard advises not use self-closing tags ("and should used"). non-binding recommendation interoperability.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -