保存到File后,编辑的XML内容不会更改

时间:2016-06-03 14:09:29

标签: java xml dom xml-parsing

我正在解析XML文件以修改所有值并保存。但保存后,没有任何变化。我做错了什么或我能做得更好?

我的目标是解析XML文件中的所有内容,检查包含特殊字符的所有字符串,并用转义字符替换它们。请不要问为什么,接收XML文档的解析器不会处理这些字符,所以我别无选择,只能逃避它们。

String xmlfile = FileUtils.readFileToString(new File(filepath));


       DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
       DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
       Document doc = docBuilder.parse(new InputSource(new StringReader(xmlfile)));

       NodeList nodeList = doc.getElementsByTagName("*");

       for (int i = 0; i < nodeList.getLength(); i++)
       {        
           Node currentNode = nodeList.item(i);

           if (currentNode.getNodeType() == Node.ELEMENT_NODE)
           {               
             if (currentNode.getFirstChild()==null)
                  {}
              else {currentNode.setNodeValue(StringEscapeUtils.escapeXml(currentNode.getFirstChild().getNodeValue())); }
           } 
       }


         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(doc);

         StringWriter writer = new StringWriter();
         StreamResult result = new StreamResult(writer);
         transformer.transform(source, result);


       FileOutputStream fop = null;
       File file;

       file = File.createTempFile("escapedXML"+UUID.randomUUID(), ".xml");

       fop = new FileOutputStream(file);

       String xmlString = writer.toString();
       byte[] contentInBytes = xmlString.getBytes();

       fop.write(contentInBytes);
       fop.flush();
       fop.close();

1 个答案:

答案 0 :(得分:2)

您正在更新Element节点,该操作无效。此外,我认为以下内容更加健壮,因为它将迭代所有文本节点,而不仅仅是第一个。

for (int i = 0; i < nodeList.getLength(); i++) {
    Node currentNode = nodeList.item(i);
    if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
        Node child = currentNode.getFirstChild();
        while(child != null) {
            if (child.getNodeType() == Node.TEXT_NODE) {
                child.setTextContent(StringEscapeUtils.escapeXml(child.getNodeValue()));
            }
            child = child.getNextSibling();
        }
    }
}