Search code examples
javaxmldom4j

detach() isn't removing element dom4j


I'm trying to remove an element from the tree using the "ref" attribute

<stock>
        <produits>
        <produit ref="1" designation="PC" qte="12" pu="123"/>
        <produit ref="2" designation="Imprimante" qte="23" pu="4578"/>
        <produit ref="3" designation="Souris" qte="243" pu="15"/>
        <produit ref="4" designation="Clavier" qte="50" pu="60"/>
        <produit ref="5" designation="Scanner" qte="34" pu="500"/>
        <produit ref="6" designation="Bureau" qte="34" pu="1500"/>
        <produit ref="7" designation="Projecteur" qte="10" pu="10000"/>
    </produits>

</stock>

Here is my function and it is not working.

public void supProduit(int ref) throws DocumentException
{
    Element root  =document.getRootElement();
    List<Node> nodesP = document.selectNodes("//Produits/Produit[@ref='"+ref+"']" );
    for (Node node : nodesP) {
       node.detach();
    }
}

Solution

  • Your XPath expression is wrong, it should be

    "//produits/produit[@ref='" + ref + "']"
    

    Element names are case-sensitive, why the list was empty.