【问题标题】:updating node attributes in xml using php使用php更新xml中的节点属性
【发布时间】:2013-04-17 11:31:03
【问题描述】:

是否可以使用 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>

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

【问题讨论】:

  • 来吧伙计们....这里需要帮助....
  • 您也可以尝试使用 phpQuery 类而不是 SimpleXML。
  • 是的。继续先生,我很高兴看到代码:)

标签: php xml simplexml


【解决方案1】:
<?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>

【讨论】:

  • 先生,是否可以使用您的代码同时更改问题和答案? @VolkerK
  • 先生,我遇到了一些愚蠢的错误......我的 xml 文件的名称是 'questions.xml'?我已经重写了我的 xml 代码的完整结构。您可以尝试定义要编辑的问题的路径吗?请..谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 2012-09-09
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多