是否可以使用 simplexml 在 xml 中插入注释标签? [英] Is it possible to insert a comment tag into an xml using simplexml?

查看:24
本文介绍了是否可以使用 simplexml 在 xml 中插入注释标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SimpleXML 构建文档,想知道是否可以像这样在文档中插入注释标签:

I am using SimpleXML to build a document, and wondering whether it is possible to insert comment tag to the document like this:

<root>
  <!-- some comment -->
  <value>
</root>

编辑:

评论位于文档中间的某个位置.

The comment is somewhere in the middle of the document.

<root>
  <tag1 />
  <!-- some comment -->
  <value />
</root>

推荐答案

不幸的是,SimpleXML 不处理注释.正如前面提到的,DOM 确实可以处理注释,但与 SimpleXML 相比,对于简单的东西使用它有点麻烦.

Unfortunately, SimpleXML doesn't handle comments. As it's been mentionned, DOM does handle comments but it's a kind of a bother to use for simple stuff, compared to SimpleXML.

我的建议:尝试 SimpleDOM.它是 SimpleXML 的扩展,所以一切都一样,它有一堆有用的方法来处理 DOM 内容.

My recommendation: try SimpleDOM. It's an extension to SimpleXML, so everything works the same and it has a bunch of useful methods to deal with DOM stuff.

例如,insertComment($content, $mode) 可以append 或插入注释beforeafter 给定的节点.例如:

For instance, insertComment($content, $mode) can append to or insert comments before or after a given node. For example:

include 'SimpleDOM.php';

$root = simpledom_load_string('<root><value/></root>');

$root->value->insertComment(' mode: append ', 'append');
$root->value->insertComment(' mode: before ', 'before');
$root->value->insertComment(' mode: after ', 'after');

echo $root->asPrettyXML();

...会回声

<?xml version="1.0"?>
<root>
  <!-- mode: before -->
  <value>
    <!-- mode: append -->
  </value>
  <!-- mode: after -->
</root>

这篇关于是否可以使用 simplexml 在 xml 中插入注释标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆