dougou6114
2012-04-27 08:57
浏览 81

如何在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>

图片转代码服务由CSDN问答提供 功能建议

我正在使用simplexml来读取xml文件。 到目前为止,我无法获得我正在寻找的属性值。 这是我的代码。

  if(file_exists($ xmlfile)){
 $ doc = new DOMDocument(); 
 $ doc-&gt; load($ xmlfile)  ; 
 $ usergroup = $ doc-&gt; getElementsByTagName(“preset”); 
 foreach($ usergroup as $ group){
 $ pname = $ group-&gt; getElementsByTagName(“name”); 
 $ att  ='code'; 
 $ name = $ pname-&gt; attributes() - &gt; $ att;  //不工作
 
 $ name = $ pname-&gt; getAttribute('code');  //不工作
 if($ name == $ preset_name){
 echo($ name); 
 $ group-&gt; parentNode-&gt; removeChild($ group); 
} 
} 
} 
}  
   
 
 

我的xml文件看起来像

 &lt; presets&gt; 
&lt; preset&gt; 
&lt;  name code =“default”&gt;默认&lt; / name&gt; 
&lt; createdBy&gt;名为&lt; / createdBy&gt; 
&lt; icons&gt; somethignhere&lt; / icons&gt; 
&lt; / preset&gt; 
&lt; / presets&gt; 
    
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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

相关推荐 更多相似问题