0

我正在阅读 XML 并更改一些属性。然后我将它作为 XML 写回文件,它返回一个空白文件。如果我不修改节点,它可以正常工作。我做错了什么,请指教。

DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                        .newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(origDrXML);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("log");
for (int i = 0; i < nodes.getLength(); i++) {
    NodeList children = nodes.item(i).getChildNodes();
int len = children.getLength();
for (int j = 0; j <= children.getLength(); j++) {
    if (children.item(j).getNodeName().equalsIgnoreCase("directory"))
        children.item(j).setTextContent("D:\\Logs");
    }
 } // End of Childrens of <log>
} // End of <log> Tag */
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
4

3 回答 3

1

您可以尝试使用空检查吗?

for (int j = 0; j <= children.getLength(); j++) {
    if(children.item(j) != null ) {
            if (children.item(j).getNodeName().equalsIgnoreCase("directory"))
                    children.item(j).setTextContent("D:\\Logs");
    }
}

这对我有用!

于 2013-03-13T17:47:02.733 回答
0

你有没有试过打电话writer.flush()前打电话writer.toString()

于 2013-03-13T17:25:09.450 回答
0

您可以尝试使用 DOMLSSerializer机制而不是Transformer. 替换所有这些:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();

有了这个

LSSerializer ser =
    ((DOMImplementationLS)doc.getImplementation()).createLSSerializer();
String xmlString = ser.writeToString(doc);
于 2013-03-13T17:38:22.363 回答