dongshi3361
2015-06-17 07:08 阅读 51

通过id获取元素并通过php中的Value xpath获取元素

XML file

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ew-language id="en">
    <global>
        <phrase id="actiondeleted" value="Deleted">
            <child_phrase_1 id="1234" value="numbers">
                <child id="test_id" value="test_value"/>
                <child id="test_id" value="test_value_2"/>
            </child_phrase_1>
        </phrase>
    </global>
</ew-language>

how to get element by ID and by value so the element is unique.I tried these

     $parent = ($xpath->query("//*[@id='$previous_tag_id']")&& $xpath->query("//*[@value='$previous_tag_value']"))->item(0);
----------------------AND THIS ONE-----------------------------------
     $parent = $xpath->query("//*[@id='$previous_tag_id']/*@value='$previous_tag_value')"->item(0);
----------------------AND THIS ONE-----------------------------------
 $xpath->query("//*[@id='$previous_tag_id' and @value='$previous_tag_value']");

each syntax is not working.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doupao3662 doupao3662 2015-06-17 14:26

    Using //*[@id='$previous_tag_id' and @value='$previous_tag_value'] should've worked, see the demo in eval.in :

    $xml = <<<XML
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <ew-language id="en">
        <global>
            <phrase id="actiondeleted" value="Deleted">
                <child_phrase_1 id="1234" value="numbers">
                    <child id="test_id" value="test_value"/>
                    <child id="test_id" value="test_value_2"/>
                </child_phrase_1>
            </phrase>
        </global>
    </ew-language>
    XML;
    $doc = new DOMDocument;
    $doc->loadXML($xml);
    $xpath = new DOMXPath($doc);
    $previous_tag_id = "test_id";
    $previous_tag_value = "test_value_2";
    $result = $xpath->query("//*[@id='$previous_tag_id' and @value='$previous_tag_value']");
    foreach($result as $r)
    {
        echo $doc->saveXML($r);
    }
    

    output :

    <child id="test_id" value="test_value_2"/>
    
    点赞 评论 复制链接分享

相关推荐