Reputation: 107
I want to remove elements (testcases) from an .xml file when the externalid (child element of testcase) is < 1000.
Testcases are always in testsuites. There can be more than one level of testsuites. So this is my .xml:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite id="" name="" >
<node_order><![CDATA[]]></node_order>
<details><![CDATA[]]></details>
<testsuite id="14162" name="Suite1" >
<node_order><![CDATA[0]]></node_order>
<details><![CDATA[]]></details>
<testsuite id="14037" name="Child Suite 1" >
<node_order><![CDATA[1]]></node_order>
<details><![CDATA[]]></details>
<testcase internalid="14038" name="Testcase 1">
<node_order><![CDATA[0]]></node_order>
<externalid><![CDATA[790]]></externalid> <---EXTERNAL ID
<version><![CDATA[1]]></version>
<steps>
<step>
<step_number><![CDATA[1]]></step_number>
<actions><![CDATA[<p>Text</p>]]></actions>
<expectedresults><![CDATA[<p>Text</p>
<p>Text</p>]]></expectedresults>
<execution_type><![CDATA[1]]></execution_type>
</step>
</steps>
</testcase>
<testcase internalid="14040" name="Testcase 2">
<node_order><![CDATA[0]]></node_order>
<externalid><![CDATA[791]]></externalid> <---EXTERNAL ID
<version><![CDATA[1]]></version>
<steps>
<step>
<step_number><![CDATA[1]]></step_number>
<actions><![CDATA[<p>Text</p>]]></actions>
<expectedresults><![CDATA[<p>Text</p>
<p>Text</p>]]></expectedresults>
<execution_type><![CDATA[1]]></execution_type>
</step>
</steps>
</testcase>
</testsuite>
<testcase internalid="14042" name="Testcase 3">
<node_order><![CDATA[0]]></node_order>
<externalid><![CDATA[792]]></externalid> <---EXTERNAL ID
<version><![CDATA[1]]></version>
<steps>
<step>
<step_number><![CDATA[1]]></step_number>
<actions><![CDATA[<p>Text</p>]]></actions>
<expectedresults><![CDATA[<p>Text</p>
<p>Text</p>]]></expectedresults>
<execution_type><![CDATA[1]]></execution_type>
</step>
</steps>
</testcase>
</testsuite>
</testsuite>
This is my php code, which won't remove the testcase.
<?php
$number = 1000;
$dom = new DOMDocument('1.0');
$dom->load('tc.xml');
$testcases = $dom->getElementsByTagName('testcase');
foreach($testcases as $tckey=>$tc)
{
$externalID = $tc->childNodes->item(3)->textContent;
if($externalID > 0 && $externalID <= $number)
{
unset($tc);
//$tc->parentNode->removeChild($tc);
//$tc->childNodes->item(3)->parentNode->removeChild($tc);
}
}
echo $dom->saveXML();
?>
What is the problem here? Why does my code not remove the testcases which have the external id <1000? Even the method with selecting the parent element won't work for me (parentNode).
Any help is welcome.
Upvotes: 1
Views: 645
Reputation: 19492
DOMNode::getElementsByTagName()
returns a live result. The list actually changes if you remove nodes. You might want to check out DOMXpath::evaluate()
. The result is not live and you can use conditions in the Xpath expressions.
$xpath = new DOMXpath($dom);
foreach ($xpath->evaluate('//testcase[externalid < 1000]') as $testCase) {
$testCase->parentNode->removeChild($testCase);
}
Upvotes: 1