dongnai5905 2010-11-17 12:04
浏览 94
已采纳

XML - 使用php从属性中获取元素子值

I'm using php to parse my xml file, all I want to be able to do is to get the element child value from the attribute:

  <question number="1">
    <type>Main</type>
  </question>

  <question number="2">
    <type>Secondary</type>
  </question>

Pseudo Code (doesn't work):

$xmlDoc = new DOMDocument(); 
$xmlDoc->load('questions.xml'); 

$searchNode = $xmlDoc->getElementsByAttribute("number"); 

foreach( $searchNode as $searchNode ) {
if ($searchnode == "1"){

$xmlType = $searchNode->getElementsByTagName( "Type" );
$valueType = $xmlType->item(0)->nodeValue;  
 echo $valueType; 

}else{
//Do nothing
}

}
  • 写回答

1条回答 默认 最新

  • dongzi1209 2010-11-17 12:17
    关注

    Use DOMXPath::evaluate

    $xp = new DOMXPath($xmlDoc);
    echo $xp->evaluate('string(/questions/question[@number=1]/type)'); // Main
    

    Note that you have to have a root node, so the above assumes there is a <questions> element. It is generally more efficient to use a direct path to the elements, but you can also query any <question> anywhere in the document with //question[… instead.

    If you want to do that without XPath, you can do

    foreach ($xmlDoc->getElementsByTagName('question') as $question) {
        if($question->getAttribute('number') === '1') {
            echo $question->getElementsByTagName('type')->item(0)->nodeValue;
            // or
            echo $question->childNodes->item(1)->nodeValue;
        }
    }
    

    Note that when using childNodes and not setting DOMDocument::preserveWhiteSpace to FALSE, any line breaks, tab stops and other whitespace will be parsed as DOMText Nodes, hence item(1) and not item(0) because the latter is a DOMText node

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题