Programme qui met à jour l'inventaire
Bonjour,
j'ai un fichier achats.txt :
Citation:
Jean Charles, 3214324565, 321, 2
Yvan Richard, 5435435545, 321, 1
Yvette Gagnon, 4324324243, 1, 12
est un fichier inventaire.xml :
Code:
1 2 3 4 5 6
| <?xml version="1.0" encoding="ISO-8859-1"?>
<inventaire>
<produit code="1" prix="432.00" quantité= "43" />
<produit code="32" prix="32.00" quantité= "100" />
<produit code="321" prix="31.00" quantité= "200" />
</inventaire> |
on mettant a jour mon fichier inventaire.xml a partir du fichier achats.txt alors que mon résultat sois :
Code:
1 2 3 4 5 6
| <?xml version="1.0" encoding="ISO-8859-1"?>
<inventaire>
<produit code="1" prix="432.00" quantité= "31" />
<produit code="32" prix="32.00" quantité= "100" />
<produit code="321" prix="31.00" quantité= "197" />
</inventaire> |
mon programme java et :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class inventaire {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder parser =
factory.newDocumentBuilder();
Document doc = parser.parse("inventaire.xml");
Element racine = doc.getDocumentElement();
NodeList nl = racine.getChildNodes();
if (args[0].equals("ajoute")) {
boolean ajout = false;
for (int k = 0; k < nl.getLength(); ++k) {
if(nl.item(k).getNodeType()==Node.ELEMENT_NODE) {
Element e = (Element) nl.item(k);
if(e.getAttribute("code").equals(args[1])) {
e.setAttribute("quantité",args[2]);
ajout=true;
}
}
}
if( ! ajout) {
Element p = doc.createElement("produit");
p.setAttribute("code", args[1]);
p.setAttribute("quantité", args[2]);
racine.appendChild(p);
}
}
TransformerFactory tfact = TransformerFactory.newInstance();
Transformer transformer = tfact.newTransformer();
transformer.setOutputProperty("encoding", "ISO-8859-1");
DOMSource source = new DOMSource(doc);
FileWriter fw = new FileWriter("inventaire.xml");
StreamResult result = new StreamResult(fw);
transformer.transform(source, result);
}
} |
mes j'arrive pas a avoir le bon résultat merci pour votre aide .