【问题标题】:How to ge two fields with one XPath?如何用一个 XPath 获得两个字段?
【发布时间】:2012-06-05 13:33:17
【问题描述】:

我有一个 XPath,它可以获取我想要读取的 div。如何用一个 XPath 读取 div 的类和名称?

【问题讨论】:

标签: php parsing xpath xml-parsing


【解决方案1】:
<?php 
        $xmlDoc = new DOMDocument(); 
        $xmlDoc->load( '<<your file>>>' ); 
    //$xmlDoc->loadHTML($sourceString); //-> if its a string you have
        $xpath = new DOMXpath($doc);
        $elements = $xpath->query("Your XPath");

        //if you are sure there is only one div, for the Xpath, you can use a index 0 in the next statement, else uou have to itereate it in a loop

    $node = $elements->item(0);

    $attrib1 = $node->attributes->getNamedItem("<attribute_name1>");
    $attrib2 = $node->attributes->getNamedItem("<attribute_name2>");
    $attrib3 = $node->attributes->getNamedItem("<attribute_name3>");
    ....



        ?> 

【讨论】:

    【解决方案2】:

    此代码选择所有具有属性名称和类的 div。请参阅下文了解如何从所选节点中选择信息。

    <?php
    
        $xmlstring = '<root>' .
            '<div name="value1" class="value2" myarg="value3"></div>' .
            '<div name="value4"></div>' .
        '</root>';
        $xml = simplexml_load_string($xmlstring);
    
        // Select all div's that have attributes name and class
        $xpath = "//div[@name and @class]"; 
        var_dump($result = $xml->xpath($xpath));
    
        /* Outputs:
            array(1) {
              [0]=>
              object(SimpleXMLElement)#3 (1) {
                ["@attributes"]=>
                array(3) {
                  ["name"]=>
                  string(6) "value1"
                  ["class"]=>
                  string(6) "value2"
                  ["myarg"]=>
                  string(6) "value3"
                }
              }
            }   
        */
    
        // note that only one iteration is performed
        // as the second div does not have an attribut
        // called 'class'.
        foreach($result as $element)
        {
            echo $element['name'];   // value1
            echo $element['class'];  // value2
        } 
    
        // or, if only one div is present in the document:
        echo $result[0]['name'];     // value1
        echo $result[0]['class'];    // value2  
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多