php xmlWriter 添加到现有节点
我遇到的情况是,有一些旧代码使用 xmlWriter 流来解析文件,并为每个文件写入一个具有该文件名的元素,当文件名唯一时,这可以正常工作。
$xml = xmlWriter
foreach file in files
$xml->startElement($fileName)
....existing logic adding file content to the new element.
$xml->endElement
但现在,需求发生了变化,我可能有同名的文件,但对于生成的 xml,每个唯一的文件名应该只有一个元素。
有没有一种简单的方法可以做到这一点而不需要改变我现有的代码太多?我知道这有点违背成为流的全部意义,但生活很糟糕,对吧?
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 are 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以看到几个解决方案,但所有这些解决方案都归结为创建多个节点。
第一个是多个文件的多个节点,但是每个文件都有一个路径属性。鉴于这些:
输出类似这样的内容:
主要好处?它允许您以几乎完全相同的方式进行创建和迭代。有损吗?它消除了该节点的parent.children 中的一个名称、一个节点。
另一种选择是创建子元素。给定相同的文件:
好处是什么?唯一文件基名和节点之间存在 1:1 关系。损害?您将需要添加递归逻辑。
考虑到这些选择,我个人会选择第一个。添加递归逻辑似乎可能会导致各种糟糕的情况和烦人的重构。但我对你的项目只有有限的了解。
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:
Output something like this:
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:
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.