簡體   English   中英

將節點附加到Java中的xml

[英]append node to an xml in Java

我無法正確地將一些信息附加到我的xml文件中。 那是抄寫員的功能

    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>";
     }
   }

和tath是我的代碼:

 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));

}

我得到錯誤Transformer Errore ...我該如何解決? 怎么了? *更新*錯誤信息

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

沒有實際的異常跟蹤或消息很難說,但我的猜測是你的問題是輸出流。

File("/azioni.xml");

是不一樣的

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

嘗試將輸出定向到系統,看看它是否有效。 即宣布抄寫員

public String scrivi (Document doc, OutputStream out)

並稱之為

scrivi(document, System.out);

更新:

要寫入相同的文件位置,請嘗試這樣的操作(未經測試)

File out = new File(getClasss()。getResource(“...”)。getFile());

並確保在嘗試寫入之前關閉最初讀取的輸入流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM