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;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题