PHP - 使用简单 XML 复制 XML 节点
我需要使用简单 XML 加载 XML 源,复制现有节点及其所有子节点,然后在渲染 XML 之前自定义此新节点的属性。有什么建议吗?
I need to load an XML source using Simple XML, duplicate an existing node with all his children, then customize an attribute of this new node before rendering XML. Any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SimpleXML 无法做到这一点,因此您必须使用 DOM 。好消息是 DOM 和 SimpleXML 是同一枚硬币 libxml 的两个侧面。因此,无论您使用的是 SimpleXML 还是 DOM,您都在处理同一棵树。下面是一个示例:
如果您经常做此类事情,可以尝试 SimpleDOM ,它是 SimpleXML 的扩展,允许您直接使用 DOM 的方法,而无需在 DOM 对象之间进行转换。
SimpleXML can't do this, so you'll have to use DOM. The good news is that DOM and SimpleXML are two sides of the same coin, libxml. So no matter whether you're using SimpleXML or DOM, you're working on the same tree. Here's an example:
If you're doing that kind of thing a lot, you can try SimpleDOM, which is an extension to SimpleXML that lets you use DOM's methods directly, without converting from and to DOM objects.
对于 SimpleXML,我发现的最好方法是解决方法。它很漂亮,但它有效:
因为它是 SimpleXML 中似乎不存在的功能的解决方法,所以您需要注意,我预计这会破坏您到目前为止定义的任何对象引用,如果有的话。
With SimpleXML, the best way I've found is a workaround. It's pretty bobo, but it works:
Since it's a workaround for a feature that doesn't seem to be there in SimpleXML, you'll need to be aware that I expect this would break any object references you've defined up to this point, if any.