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条)

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用