0

I am trying to delete a node using XPATH and php, while coming two XPATH queries.

I am using php 5 for such problem. I tried to use DOMDocument with no luck.

enter code here
//The php file
$xml_str = file_get_contents("projectTest.xml");
$xml = new SimpleXMLElement($xml_str);


echo $xml->saveXML();
unset($xml->xpath("/project/Item/username[@date='2019-04-20'] and 
/project/Item/username/clientID[text()=='10000']")[0]->{0});
echo $xml->saveXML();



//The XML File
<project>   
   <Item>
     <username date="2019-04-20">
      <clientID>10000</clientID>
     </username>
     <name>Test1</name>
     <price>200</price>
     <quantity>1</quantity>
  </Item>
  <Item>
    <username date="2019-06-23">
      <clientID>3</clientID>
    </username>
    <name>Test2</name>
     <price>200</price>
   <quantity>1</quantity>

 </Item>

enter code here

<!-------- Expected:
  <project>
    <Item>
       <username date="2019-06-23">
         <clientID>3</clientID>
       </username>
       <name>Test2</name>
       <price>200</price>
      <quantity>1</quantity>

   </Item>
</project>

Actual results: The above code is generating errors. P.S: I just started to learn how to use XPATH, i am having problem in understanding how the syntax works.

hansley
  • 260
  • 1
  • 7
  • 2
    _generating errors_ you say? – AbraCadaver Apr 25 '19 at 16:58
  • Yes, Warning: SimpleXMLElement::xpath(): Invalid expression; SimpleXMLElement::xpath(): xmlXPathEval: evaluation failed ; – hansley Apr 25 '19 at 17:02
  • 2
    to add or remove nodes you would not use `unset` - instead to remove it might be `removeChild`, to add `appendChild` etc supposing that you are indeed using `DOMDocument` - I imagine `SimpleXMLElement` has it's own methods for these tasks but not `unset` – Professor Abronsius Apr 25 '19 at 17:14
  • For SimpleXML, have a look at https://stackoverflow.com/a/394722/1213708 – Nigel Ren Apr 26 '19 at 14:35

1 Answers1

3

It's difficult to reverse engineer your requirements from incorrect code, but I suspect that

"/project/Item/username[@date='2019-04-20'] and 
/project/Item/username/clientID[text()=='10000']"

should be

"/project/Item/username[@date='2019-04-20' and clientID='10000']"

and is a boolean operator, if you apply it to two node-sets the result is true if both node-sets are non-empty; the final result of the expression is therefore a boolean, not a node-set.

The syntax error is because the XPath equality operator is "=", not "==".

Michael Kay
  • 156,231
  • 11
  • 92
  • 164