使用php更新XML中的节点属性


updating node attributes in xml using php

是否可以使用simplexml更新xml的节点属性?示例:我的程序其实是一个教师问答编辑器,作为一名教师,我想编辑一个特定的问题属性。即

<Quiz>
<topic text="Preparation for Exam">
    <subtopic text="Math">
              <question text="1 + 1 = ?"> 
              <answer num="A" Text="1" /> 
              <answer num="B" Text="2" /> 
              <answer num="C" Text="3" /> 
              <answer num="D" Text="4" /> 
              </question>
              <question text="4 * 4 = ?" > 
              <answer num="A" Text="12" /> 
              <answer num="B" Text="14" /> 
              <answer num="C" Text="16" /> 
              <answer num="D" Text="18" /> 
              </question>
       </subtopic>
       </topic>
       </Quiz>

是可能的吗?虽然我已经尝试了很多方法,即删除以前的节点,然后插入编辑过的一个。但这个技巧只适用于最后一个节点…对于其他节点,它只执行交换

<?php
$subtopic = new SimpleXMLELement(data());
$subtopic->question[1]['text'] = 'lalala';
$subtopic->question[1]['foo'] = 'bar';
foreach( $subtopic->question[1]->answer as $answer) {
    $answer['Text'] .= '(dez)';
}
echo $subtopic->asXML();

function data() {
    return <<< eox
<subtopic text="Math">
<question text="1 + 1 = ?"> 
<answer num="A" Text="1" /> 
<answer num="B" Text="2" /> 
<answer num="C" Text="3" /> 
<answer num="D" Text="4" /> 
</question>
<question text="4 * 4 = ?" > 
<answer num="A" Text="12" /> 
<answer num="B" Text="14" /> 
<answer num="C" Text="16" /> 
<answer num="D" Text="18" /> 
</question>
</subtopic>
eox;
}

打印

<?xml version="1.0"?>
<subtopic text="Math">
<question text="1 + 1 = ?"> 
<answer num="A" Text="1"/> 
<answer num="B" Text="2"/> 
<answer num="C" Text="3"/> 
<answer num="D" Text="4"/> 
</question>
<question text="lalala" foo="bar"> 
<answer num="A" Text="12(dez)"/> 
<answer num="B" Text="14(dez)"/> 
<answer num="C" Text="16(dez)"/> 
<answer num="D" Text="18(dez)"/> 
</question>
</subtopic>