开发者

php xmlWriter adding to existing node

I have a situation where there was some old code which uses xmlWriter stream to parse files, and for each file write an element with that file name, this works fine when the file names ar开发者_运维知识库e unique.

$xml = xmlWriter
foreach file in files
    $xml->startElement($fileName)
        ....existing logic adding file content to the new element.   
    $xml->endElement

But now, the requirement changed and i might have files with same name, but for the produced xml there should only be one element per unique file name.

Is there an easy way i can do this w/o changing my existing code much? i know this is kind of against the whole point of being a stream, but life sucks, right?


I can see a couple of solutions, but all of them boil down to creating multiple nodes.

The first is multiple nodes for multiple files, but each file has a path attribute. Given these:

$fl1 = '/home/the_spleen/spleen.txt';
$fl2 = '/home/the_bowler/not_enough_beer/spleen.txt';

Output something like this:

<spleen path='/home/the_spleen/'><!-- spleenerficy --></spleen>
<spleen path='/home/the_bowler/not_enough_beer/'><!-- no. just no. --></spleen>

Major benefit? it allows you to create and iterate in almost exactly the same way you were. Detriment? It gets rid of the one name, one node in that node's parent.children.

The other option would be to create sub-elements. Given the same files:

<spleen>
   <fl path='/home/the_spleen/'><!-- fl-ify! --></fl>
   <fl path='/home/the_bowler/not_enough_beer/'><!-- drink! --></fl>
</spleen>

The benefit? There is a 1:1 relationship between unique file basenames and nodes. The detriment? You're going to need to add recursion logic.

Given those choices, I would go with the first, personally. Addition of recursion logic just seems like it could lead to all sorts of badness and annoying re-factoring. But I only have a limited view of your project from here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜