使用xpath添加SimpleDOM的注释

问题描述:

我想在xml文件中添加注释到特定的元素,每个元素都有它的唯一名称。我的文件是一个翻译文件,以便它仅包含字符串元素和复数等使用xpath添加SimpleDOM的注释

下面是我用我的第一个添加评论尝试的片段:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
     <string name="debug">You wish you could use that!</string> 
     <string name="author">foobar</string> <!-- Insert author name here --> 
     <string name="error">Wutfuq</string> <!-- New! --> 
</resources> 

在这里,我的PHP文件,我尝试给名称为“debug”的元素添加注释:

<?php 
error_reporting(E_ALL); 
include "SimpleDOM.php"; 

$xml = simpledom_load_file("strings.xml"); 

$xml->xpath("//string[@name='debug']")->insertComment(' This is a test comment ', 'after'); 
$xml -> asXML('test.xml'); 
echo "This line should be shown, otherwise there might be some error"; 
?> 

所以我的问题是,这是行不通的。 整个页面是白色的,没有错误,我的test.xml将不会被创建,所以这个错误似乎是我在使用xpath时添加注释的那一行。

我很感激的帮助,请不要试图说服我使用DOM。

According to the PHP doc,SimpleXMLElement :: xpath()返回一个数组。你不能用insertComment()来链接它。

编辑: 您可以使用isertComment与SimpleDom但只值:

$result = $xml->xpath("//string[@name='debug']") 
$result[0]->insertComment(' This is a test comment ', 'after'); // after, append or before 
$xml->asXML('test.xml'); 
+0

好。那么访问具有name =“debug”属性的特定元素(字符串)的正确方法是什么? –

+0

谢谢,这个技巧,虽然我会像这样使用它:current($ xml-> xpath(“// string [@ name ='debug']”)) - > insertComment('This is a test评论','之后'); –

+0

也请修复您制作的拼写错误。 有些人可能会复制代码,它会返回错误,因为您在第一行有错字($ resul)。 –