dongrong7267 2018-11-08 11:14
浏览 151

如果节点存在Xpath,则修改属性?

I'm trying to modify a node attribute if the node exist or create it if not in a xml file using Xpath. xml file looks like that :

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

and here is my php code :

<?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);

?>

if the node doesn't exist then it's added, no problem, but if it exist the attribute values aren't changed.

  • 写回答

1条回答 默认 最新

  • douhuang3833 2018-11-08 11:22
    关注

    You can't alter attributes like that with XPath,

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

    you just need to modify them directly from the hotspot you already have...

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料