修改后无法写回XML

时间:2013-03-13 17:12:34

标签: java xml xml-parsing

我正在阅读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);

3 个答案:

答案 0 :(得分: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");
    }
}

这对我有用!

答案 1 :(得分:0)

您是否尝试在致电writer.flush()之前致电writer.toString()

答案 2 :(得分:0)

您可以尝试使用DOM LSSerializer机制而不是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);