JAVA修改XML文件

时间:2015-08-05 05:55:30

标签: java exception xml.modify

我正在尝试从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号线评论道。 等待解决,谢谢!

1 个答案:

答案 0 :(得分:1)

由于路径中的前导p字符,/数组中已生成[space]字符

您可以从原始路径移除/ ...

update_xml(doc, "jdbc/url", url);
update_xml(doc, "jdbc/username", user);
update_xml(doc, "jdbc/password", pass);
update_xml(doc, "jdbc/name", baze);

将摆脱即时错误

  

现在我没有收到任何错误,但也没有对文件进行任何更改。

您的示例代码都没有显示您实际将Document保存回文件,一旦加载,DOM与其来源之间没有关联,您需要自己保存内容,例如...

DOMSource domSource = new DOMSource(doc);
try (FileOutputStream fos = new FileOutputStream(f)) {
    StreamResult sr = new StreamResult(fos);
    tf.transform(domSource, sr);
}