如果节点存在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个回答

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;
doujin8673
doujin8673 请考虑将此标记(以及您的任何其他问题)标记为已解答 - meta.stackexchange.com/questions/5234 / ...
接近 2 年之前 回复
dongxie1907
dongxie1907 太棒了!!! 很多,你做了我的一天;)
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐