dougou6114 2012-04-27 08:57
浏览 101
已采纳

如何在php中获取xml节点的属性值?

I'm using simplexml to read a xml file. So far i'm unable to get the attribute value i'm looking for. this is my code.

          if(file_exists($xmlfile)){
              $doc = new DOMDocument();
              $doc->load($xmlfile);
              $usergroup = $doc->getElementsByTagName( "preset" );
              foreach($usergroup as $group){         
                 $pname = $group->getElementsByTagName( "name" );
                 $att = 'code';
                 $name = $pname->attributes()->$att; //not working

                 $name = $pname->getAttribute('code'); //not working
                 if($name==$preset_name){
                     echo($name);
                      $group->parentNode->removeChild($group);
                 }
              }
          }

and my xml file looks like

<presets>
<preset>
 <name code="default">Default</name>
  <createdBy>named</createdBy>
  <icons>somethignhere</icons>
 </preset>
</presets>
  • 写回答

2条回答 默认 最新

  • duanhua9398 2012-04-30 01:49
    关注

    Actually question in my head includes deleting a node as well , mistakenly i could not add it. So in my point of view this is the complete answer, i a case if someone else find this useful. This answer doesn't include SimpleXMLElement class because how hard i tried it didn't delete the node with unset(); . So back to where i was , i finally found an answer. This is my code. and its Simple!!!

    if(file_exists($xmlfile)){
                  $doc = new DOMDocument();
                  $doc->load($xmlfile);
                  $presetgroup = $doc->getElementsByTagName( "preset" );
                  foreach($presetgroup as $group){       
                     $pname = $group->getElementsByTagName( "name" );
                      $pcode = $pname->item(0)->getAttribute('code');
                     if($pcode==$preset_name){
                          echo($preset_name);
                          $group->parentNode->removeChild($group);
                     }
                  }
              }
            $doc->save($xmlfile);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论
  • ¥15 keil5 target not created
  • ¥15 C/C++数据与算法请教
  • ¥15 怎么找志同道合的伙伴
  • ¥20 如何让程序ab.eXe自已删除干净硬盘里的本文件自己的ab.eXe文件
  • ¥50 爬虫预算充足,跪巨佬
  • ¥15 滑块验证码拖动问题悬赏
  • ¥15 Wanted but not invoked:Actually, there were zero interactions with this moc
  • ¥20 怎么驱动tb6612