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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题