Output of Xpath Query

2019-09-07 00:02发布

问题:

First I would like to ask what is the format of the output of the Xpath query.

For me when I do the view source of my output I get view-source

actual output - output

Sample xml - xmlfile

My php code -

<?php

$variable=$_POST['module']; 
$xmldoc = new DOMDocument();
        $xmldoc->load('info.xml');

        $xpathvar = new Domxpath($xmldoc);

        $queryResult = $xpathvar->query("testcase[substring-after(
        substring-after(script, '/'),
        '/'
    ) = '$variable' or
    substring-before(
        substring-after(
            substring-after(script, '/'),
            '/'
        ),
        '/'
    ) = '$variable']"); 

foreach($queryResult as $var)
        {
                echo $var->textContent;
                echo "\n";
        }

?>

What I want is to get the string ending with .tcl instead of full content

pls help !!

回答1:

First you're looking only for a testcase element node, the actual path to the textcase nodes is /testcaseInfo/testcase and can be optimized to any testcase element in the document:

//testcase

Next to validate if an element ends with a string you copy that part of the string and compare it.

//testcase[ substring( script, string-length(script) - string-length('.tcl') + 1 ) = '.tcl' ]

This will return the testcase element nodes, now you can use detail expression to fetch the data for each testcase:

Example:

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$expression = "
  //testcase[
    substring(
      script, 
      string-length(script) - string-length('$module') + 1
    ) = '$module'
  ]
";

// iterate test test cases and get name/script strings contents
foreach ($xpath->evaluate($expression) as $testCase) {
  var_dump(
    $xpath->evaluate('string(name)', $testCase),
    basename($xpath->evaluate('string(script)', $testCase))
  );
}     

Output: https://eval.in/120110

string(59) "802.1x_2.52_RADIUS_Accounting_AVP_contains_client_static_IP"
string(31) "802dot1xRadAccAVPClntStatIp.tcl"
string(27) "802.1x_1.02_Basic_User_Mode"
string(25) "802dot1xBasicUserMode.tcl"
string(44) "802.1x_2.47_RADIUS_Accounting_Enable_Disable"
string(34) "802dot1xRadiusAccEnableDisable.tcl"
string(31) "802.1x_2.14_RADIUS_Assigned_CoS"
string(29) "802dot1xRadiusAssignedCos.tcl"
...