douzhongqiu5032 2018-06-03 04:52
浏览 44
已采纳

PHP:查找孩子并更新同一父母下的另一个孩子

Can someone please help me to get this working? I'm trying to find a child in the below XML and once it is found, I need to update another child within the same parent node. It can be either in simpleXML or XDOM - using both I managed to work out how to find the item but I can't figure out how to update another child within the same parent.

So in the below example, I want to first find the skill 'Maths' and update the 'level' to some other number.

XML:
<map>
<competency>
  <level>5</level>
  <skill name="Maths"> 
     <skillinfo> "some value" </skillinfo>
  </skill>
<competency>
</map>

So far I've: 

$dom = new DOMDocument;
$dom->loadXML($data);
$xpath = new DomXpath($dom);

I don't really need a for loop as the skill only appears once in the XML, so more like IF this skill exists then update the level.

foreach ($xpath->query('//skill[@name="Maths"]') as $item) {
echo $item->nodeValue;
// how to update the child 'Level'?
}

Once the change is made I will then need to append the changes to the XML file.

2nd part of the question:

How to output everything inside an XML file using DOM.

Below works but only shows child VALUES under the parent however what I'd like to ouput is the name value which in this example is .

$dom = new DOMDocument;
$dom->loadXML($data);
$xpath = new DomXpath($dom);
$x = $dom->documentElement;
foreach ($x->childNodes AS $item){
print $item->nodeName . " = " . $item->nodeValue . "<br />";
}
  • 写回答

2条回答 默认 最新

  • dst3605528 2018-06-03 08:05
    关注

    You Can do by using the it parentNode attribute and then loop on all childs. As follow:

    $data = '<map><competency><level>5</level><skill name="Maths"><skillinfo>"some value"</skillinfo></skill></competency></map>';
    $dom = new DOMDocument;
    $dom->loadXML($data);
    $xpath = new DomXpath($dom);
    foreach ($xpath->query('//skill[@name="Maths"]') as $item) {
            foreach($item->parentNode->childNodes as $node)
                    if ($node->tagName == 'level')
                            $node->nodeValue = @WhatEverValueYouWant@;
    }
    $xml_string = $dom->saveXML();
    echo $xml_string;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c