gpt4 book ai didi

java - 在 Java 中将节点 append 到 xml

转载 作者:行者123 更新时间:2023-12-02 07:08:55 24 4
gpt4 key购买 nike

我无法将某些信息正确 append 到我的 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>";
}
}

这是我的代码:

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

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

public String scrivi (Document doc, OutputStream out)

并调用它

scrivi(document, System.out);

更新:

要写入同一文件位置,请尝试类似的操作(未经测试)

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

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

关于java - 在 Java 中将节点 append 到 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com