i am facing some problem for this following codes
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("subcompany");
doc.appendChild(rootElement);
//id elements
Element id = doc.createElement("id");
id.appendChild(doc.createTextNode(subCompanyId != null ? subCompanyId : " "));
rootElement.appendChild(id);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
String xmlPath = "/project/MallDirectory/mall";
//EDITED for File creation before writing.
boolean isFileCreated = new File(xmlPath, "subcompany.xml").createNewFile();
System.out.println(isFileCreated);
StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));
transformer.transform(source, result);
} catch (Exception ex) {
ex.printStackTrace();
}
After i run, i get this following error:
javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)
It used to work on my other project, however not this time round. What exactly went wrong here ?
EDITED:
Here is the path that i am trying to write into. The file is created, but it is empty.
I managed to solve the problem.
Here is the Error:
javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)
I am thinking maybe the transformer is trying to write the xml to this path 'file:/project/MallDirectory/mall/subcompany.xml'. I don't know how it happened, as i have specifically set the file path '/project/MallDirectory/mall/subcompany.xml', and does not prefixed with 'file:/'.
Therefore, i somehow managed to fix it by doing this:
...
//ERROR CODE:
//StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));
//
StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml").getPath());
transformer.transform(source, result);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With