Jump to content

place xml closing tags on newline for empty nodes only


davidkierz

Recommended Posts

i need to replicate this strange dotnet behavior exactly.

 

<?xml version="1.0"?>
<library>
   <book>
       <Title>Green Eggs And ham</Title>
       <page>
       </page>
   </book>
</library>
 
nodes that are empty have the closing tag on a new, indented line. Nodes with content have the closing on the same line.
 
in php, i am saving my xml with $xml = $dom->saveXML($dom, LIBXML_NOEMPTYTAG) which pretty closely matches this, with the excepton of empty nodes having the closing tag on the same line
 
<?xml version="1.0"?>
<library>
   <book>
       <Title>Green Eggs And ham</Title>
       <page></page>
   </book>
</library>

i dont see option for placing closing tags for empty nodes on new lines, any ideas how i can go about recreating this behavior?

 

Why do you have to replicate that? Putting the end tag on a newline changes the content: it's not an empty node anymore but a node with a bunch of whitespace as its value.

 

Whatever. Try regular expressions to replace "the beginning of the line, whitespace, and " with "the whitespace, , newline, the whitespace again, and ".

preg_replace('#^(\s+)$#m', '$1\n$1', $xml)

okay i think what ill do it break the string into an array of lines

check each line to see if its empty

if it is remove the closing tag, count how many indents, insert new indented line into array with closing tag

 

EDIT

the xml is encoded into binary and encrypted, signed, and hashed i need to create the exact same output. this is the only difference.

there are thousands of different tags that may or may not be empty, my example is only a simplification
    $linnewline = "\n";
    $emptyline = "></";
    $lines = explode($linnewline,$xml);
    unset($xml);
    $xml = "";
    foreach ($lines as $line) {
        if (strpos($line,$emptyline) !== false) {
            $spaces = 0;
            for ($i = 0; $i<strlen($line); $i++){
                if ($line[$i] != " "){
                    break;
                }
                $spaces=$spaces+1;
            }
            $split = explode($emptyline, $line);
            $newline = $split[0] . ">\n" . str_repeat(" ", $spaces) . "</" . $split[1];
            $xml = $xml . $newline . $linnewline;
        } else {
            $xml = $xml . $line . $linnewline;
        }
    }

ugh.. its ugly and slow. but it works..

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.