Java读取XML并将文本节点放入字符串数组中?

时间:2014-07-07 02:43:19

标签: java xml

如果有人问过这个问题,我很抱歉,我一直在谷歌搜索超过一个小时,似乎无法弄清楚如何做到这一点。

我为我正在制作的应用程序创建了一个配置文件,该文件存储在XML中,如果使用DOM不存在,我已经让应用程序成功创建了XML文件,

(代码,如果需要的话)

    public static void newConfig() {
    try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root element
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("settings");
        doc.appendChild(rootElement);

        // address element
        Element address = doc.createElement("address");
        address.appendChild(doc.createTextNode("127.0.0.1"));
        rootElement.appendChild(address);

        // port element
        Element port = doc.createElement("port");
        port.appendChild(doc.createTextNode("3306"));
        rootElement.appendChild(port);

        // user element
        Element user = doc.createElement("user");
        user.appendChild(doc.createTextNode("user"));
        rootElement.appendChild(address);

        // password element
        Element pass = doc.createElement("pass");
        pass.appendChild(doc.createTextNode("password"));
        rootElement.appendChild(pass);

        // database element
        Element datab = doc.createElement("database");
        datab.appendChild(doc.createTextNode("A1"));
        rootElement.appendChild(datab);

        // write the content to XML
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("config.xml"));
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(source, result);

        } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
        } catch (TransformerException tfe) {
        tfe.printStackTrace();
        }

        }

创建了这个:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<settings>
<port>3306</port>
<address>127.0.0.1</address>
<pass>password</pass>
<database>A1</database>
</settings>

我如何将这些文本节点检索为字符串数组?

1 个答案:

答案 0 :(得分:0)

试试这个

    NodeList nodes = docBuilder.parse(new File("1.xml")).getDocumentElement().getChildNodes();
    String[] a = new String[4];
    for (int i = 0, j = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        if (n instanceof Element) {
            a[j++] = n.getTextContent().trim();
        }
    }