【发布时间】:2019-04-11 21:29:25
【问题描述】:
如果节点存在,我正在尝试修改节点属性,如果不存在,则使用 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);
?>
如果节点不存在,则添加它,没问题,但如果存在,则属性值不会更改。
【问题讨论】: