简体   繁体   中英

append node to an xml in Java

I can't append correctly some info to my xml file. That's the scrivi function

    public String scrivi (Document doc, File dest)
   {
     try
     {

        DOMSource sorgente = new DOMSource (doc);
        StreamResult sr = new StreamResult (dest);        
        TransformerFactory tf =
            TransformerFactory.newInstance();
        Transformer transf = tf.newTransformer();
        transf.transform (sorgente, sr);
        return "Tutto ok";
     }
     catch (TransformerConfigurationException tce)
     {

        System.out.println(tce.getMessage());
        return  "<h1> Config </h1>";
     }
     catch (TransformerException te)
     {

        System.out.println(te.getMessage());
        return "<h1> Transformer Errore </h1>";
     }
   }

and tath is my code:

 try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document document = db.parse(getClass().getResourceAsStream("/azioni.xml"));


            Element root = document.getDocumentElement(); 
            Element new_azione = document.createElement("azione");
            Element id = document.createElement("id_azione");
            id.setTextContent(id_azione);
            Element nome = document.createElement("nome_azione");
            nome.setTextContent(nome_azione);
            Element prezzo_a = document.createElement("prezzo");
            prezzo_a.setTextContent(prezzo);
            new_azione.appendChild(id);
            new_azione.appendChild(nome);
            new_azione.appendChild(prezzo_a);
            document.getDocumentElement().appendChild(new_azione);



            String nomexmlOut="/azioni.xml";



            File filedest = new File(nomexmlOut); 


            out.println(this.scrivi(document, filedest));

}

I get the error Transformer Errore ... how can I solve? what's Wrong? * UPDATE * Error Info

java.io.FileNotFoundException: /azioni.xml (Permission denied)

Hard to tell without actual exception trace or message, but my guess is that your problem is the ouput stream.

File("/azioni.xml");

is not the same as

getClass().getResourceAsStream("/azioni.xml")

Try with directing the output to system out and see if it works. ie declare scrivi

public String scrivi (Document doc, OutputStream out)

and call it with

scrivi(document, System.out);

UPDATE:

To write to the same file location, try something like this (untested)

File out = new File(getClasss().getResource("...").getFile());

and make sure that you close the input stream that you originally read from, before trying to write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM