PHP SimpleXML 可选子节点


PHP SimpleXML Optional Child Nodes

我正在尝试根据子节点的子节点分隔子节点,但我无法弄清楚如何验证节点是否有值。

这是我的 XML:

<?xml version="1.0"?>
<testcase>
 <steps>
 <step id="one">
    <command>gettitle</command>
 </step>
 <step id="two">
    <command>click</command>
    <parameter>id=searchByAddressSubmit</parameter>
 </step>
 </steps>
</testcase>

这是我的代码:

$testcase = new SimpleXMLElement($xml);
foreach($testcase->steps->step as $step) {
    echo $step->parameter;
    echo $step->command;    
    if(empty($step->parameter)) {
        echo $step>command;
    }
} 

结果应该是:

gettitle

我已经尝试了 empty()、array_key_exists() 和 is_null(),但似乎没有什么选择缺失值。有什么想法吗?

如果它确实是一个拼写错误并且您没有得到任何输出,则仅表示您在此行上有一个错误:

echo $step>command;

应该是->.

如果您已打开错误报告,它应该会给出一条错误消息:

注意:使用未定义的常量命令 - 假定"命令"

这应该是:

// turn on error reporting on development
error_reporting(E_ALL);
ini_set('display_errors', '1');
$testcase = new SimpleXMLElement($xml);
foreach($testcase->steps->step as $step) {   
    if(empty($step->parameter)) {
        echo $step->command; // fixed arrow operator
    }
}

输出