I'm trying to modify my Config.xml file from JAVA program, file contains data about MySql connection.
Here's the code after button click:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
File f = new File("Config.xml");
Document doc = domFactory.newDocumentBuilder().parse(f.getAbsolutePath());
String url = server_field.getText();
String user = db_login_field.getText();
String pass = db_pass_field.getText();
String baze = db_name_field.getText();
klases.update_xml(doc, "jdbc/url", url);
klases.update_xml(doc, "jdbc/username", user);
klases.update_xml(doc, "jdbc/password", pass);
klases.update_xml(doc, "jdbc/name", baze);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer tf = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
try (FileOutputStream fos = new FileOutputStream(f)) {
StreamResult sr = new StreamResult(fos);
tf.transform(domSource, sr);
}
update_xml function:
public static void update_xml(Document doc, String path, String def) {
String p[] = path.split("/");
//search nodes or create them if they do not exist
Node n = doc;
for (int i = 0; i < p.length; i++) {
NodeList kids = n.getChildNodes();
Node nfound = null;
for (int j = 0; j < kids.getLength(); j++) {
if (kids.item(j).getNodeName().equals(p[i])) {
nfound = kids.item(j);
break;
}
}
if (nfound == null) {
nfound = doc.createElement(p[i]); // LINE 300
n.appendChild(nfound);
n.appendChild(doc.createTextNode("\n")); //add whitespace, so the result looks nicer. Not really needed
}
n = nfound;
}
NodeList kids = n.getChildNodes();
for (int i = 0; i < kids.getLength(); i++) {
if (kids.item(i).getNodeType() == Node.TEXT_NODE) {
//text node exists
kids.item(i).setNodeValue(def); //override
return;
}
}
n.appendChild(doc.createTextNode(def));
}
And here is XML file:
<?xml version="1.0" encoding="UTF-8"?>
<jdbc>
<url>localhost:3306</url>
<driver>com.mysql.jdbc.Driver</driver>
<username>username</username>
<password>password</password>
<name>database</name>
</jdbc>
And here's the error:
Exception in thread "AWT-EventQueue-0" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.createElement(CoreDocumentImpl.java:622)
at programa.klases.update_xml(klases.java:300)
Line 300 commented. Waiting for soliution, thank you!