2013-11-04 35 views
0

我想在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。

回答

0

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)。 –