【问题标题】:append node to an xml in Java将节点附加到Java中的xml
【发布时间】:2013-03-24 08:30:38
【问题描述】:

我无法将某些信息正确地附加到我的 xml 文件中。这就是scrivi函数

    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)

【问题讨论】:

  • 显示完整的错误,以便我们查看它的来源。

标签: java xml servlets append


【解决方案1】:

如果没有实际的异常跟踪或消息,很难说,但我猜你的问题是输出流。

File("/azioni.xml");

和

不一样
getClass().getResourceAsStream("/azioni.xml")

尝试将输出定向到系统输出,看看它是否有效。即声明 scrivi

public String scrivi (Document doc, OutputStream out)

并调用它

scrivi(document, System.out);

更新:

要写入相同的文件位置,请尝试这样的操作(未经测试)

文件输出 = new File(getClasss().getResource("...").getFile());

并确保在尝试写入之前关闭最初读取的输入流。

【讨论】:

  • 好吧,那我是对的。您或进程没有写入/创建输出文件的权限。尝试不使用前导斜杠 ('/');
  • 我替换了字符串 nomexmlOut="/azioni.xml";使用字符串 nomexmlOut="azioni.xml";但我得到相同的结果 java.io.FileNotFoundException: /azioni.xml (Permission denied)
  • 我确定该文件存在,因为 Document document = db.parse(getClass().getResourceAsStream("/azioni.xml"));我可以读取文件...我需要添加一个节点并更新它...这就是问题
  • 好的,但同样,File("/name") 与 class.getResource() 不同。查看更新
  • 非常感谢您的耐心等待......它就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多