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 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?