如果节点与Xpath一起存在,是否修改属性?

时间:2018-11-08 11:14:29

标签: php xpath nodes simplexml

我正在尝试修改节点属性(如果该节点存在),或者如果不使用Xpath在xml文件中创建该属性。 xml文件如下所示:

<krpano>
    <hotspot name="hs1" ath="0" atv="0"/>
    <hotspot name="hs2" ath="0" atv="0"/>
</krpano>

这是我的php代码:

<?php
$str_json = file_get_contents('php://input');
$json_data = json_decode($str_json);

$file = 'myxmlfile.xml';
$xml = simplexml_load_file($file);
$krpano = $xml->xpath("//krpano");
$hotspot = $xml->xpath('//hotspot[@name="'.$json_data->name.'"]');

if ($hotspot){
    $xml->xpath('//hotspot[@name="'.$json_data->name.'"]/@ath->'.$json_data->xpos.'');
    $xml->xpath('//hotspot[@name="'.$json_data->name.'"]/@atv->'.$json_data->ypos.'');
}else{
    $newhs = $krpano[0]->addChild('hotspot');
    $newhs->addAttribute('name', $json_data->name);
    $newhs->addAttribute('ath', $json_data->xpos);
    $newhs->addAttribute('atv', $json_data->ypos);
}

$xml->asXML($file);

?>

如果该节点不存在,则可以添加它,这没问题,但是如果该节点存在,则属性值不会更改。

1 个答案:

答案 0 :(得分:0)

您无法使用XPath更改属性,

$xml->xpath('//hotspot[@name="'.$json_data->name.'"]/@ath->'.$json_data->xpos.'');
$xml->xpath('//hotspot[@name="'.$json_data->name.'"]/@atv->'.$json_data->ypos.'');

您只需要直接从已有的热点中修改它们...

$hotspot[0]['ath'] = $json_data->xpos;
$hotspot[0]['atv'] = $json_data->ypos;