Issue
i have this method adn i have to remove all the orders from the same client. here is the .xml file from which i am removing
<encomendas>
<encomenda cod="enc4" data="2016-04-23" cliente="cli5" status="pendente">
<enc quant="3">9789722523288</enc>
<enc quant="1">9789726656272</enc>
</encomenda>
<encomenda cod="enc5" data="2016-05-16" cliente="cli7" status="pendente">
<enc quant="1">9789720043702</enc>
<enc quant="1">9789724146348</enc>
<enc quant="2">9789724121390</enc>
<enc quant="1">9789720046451</enc>
</encomenda>
<encomenda cod="enc6" data="2016-04-23" cliente="cli5" status="pendente">
<enc quant="3">9789722523288</enc>
<enc quant="1">9789726656272</enc>
</encomenda>
</encomendas>
and here is the code that i made
@WebMethod(operationName = "removeorder2")
public String removeorder2(@WebParam(name = "cliente") String id) {
URL u = this.getClass().getResource("orders.xml");
Document doc = XMLJDomFunctions.lerDocumentoXML(u.getFile());
Element encomendas = doc.getRootElement();
for (int i = 0; i < encomendas.getChildren().size(); i++) {
Element filho = encomendas.getChildren().get(i);
if (filho.getAttribute("cliente").getValue().equals(id)) {
encomendas.getChildren().remove(i);
XMLJDomFunctions.escreverDocumentoParaFicheiro(doc, u.getFile());
return "order removed";
}
}
return "order doesnt exist";
}
but like this i am only removing one when i insert the client that i want remove. For example if i insert cli5 it will remove the first cli5 that he finds. I have do a cicle while but i don't know how to, do I make an xpath counting how many clients i have or there are easy ways to do it?
Solution
It's because you return the method immediately when you remove something. You can take return "order removed";
out of the for loop, and have something like a flag variable to check whether there's something removed.
@WebMethod(operationName = "removeorder2")
public String removeorder2(@WebParam(name = "cliente") String id) {
boolean check = false;
URL u = this.getClass().getResource("orders.xml");
Document doc = XMLJDomFunctions.lerDocumentoXML(u.getFile());
Element encomendas = doc.getRootElement();
for (int i = 0; i < encomendas.getChildren().size(); i++) {
Element filho = encomendas.getChildren().get(i);
if (filho.getAttribute("cliente").getValue().equals(id)) {
encomendas.getChildren().remove(i);
XMLJDomFunctions.escreverDocumentoParaFicheiro(doc, u.getFile());
check = true;
}
}
if (check) return "order removed";
return "order doesnt exist";
}
One other thing is about the remove logic. Let say you remove an item at index 1, and so the next item will have index 1, right. But in the next interaction, you go the index 2, and the third item now is at index 1 will be skipped? So I guess you have to recheck the index of the next item and make sure you're not skipping anything.
Btw, what is the method escreverDocumentoParaFicheiro
?
Answered By - berong91
Answer Checked By - Terry (JavaFixing Volunteer)