简体   繁体   English

修改后无法写回XML

[英]Unable to write XML back after modification

I am reading a XML and changing some attributes. 我正在阅读XML并更改一些属性。 Then I am writing it back to file as XML and it returns me a blank file. 然后,我将其写回XML格式的文件中,并返回一个空白文件。 If I don't modify the node it works fine. 如果我不修改节点,它将正常工作。 What I am doing wrong, please advice. 我做错了,请指教。

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);

Can you try with a null check? 您可以尝试使用空检查吗?

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");
    }
}

This works for me! 这对我有用!

您是否曾在调用writer.flush()之前尝试调用writer.toString()

You could try using the DOM LSSerializer mechanism instead of a Transformer . 您可以尝试使用DOM LSSerializer机制而不是Transformer Replace all this: 替换所有这些:

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();

with this 有了这个

LSSerializer ser =
    ((DOMImplementationLS)doc.getImplementation()).createLSSerializer();
String xmlString = ser.writeToString(doc);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM