我正在尝试从 JAVA 程序修改我的 Config.xml 文件,该文件包含有关 MySql 连接的数据。
这是单击按钮后的代码:
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 函数:
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));
}
这是 XML 文件:
<?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>
这是错误:
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)
第 300 行评论。等待解决,谢谢!