繁体   English   中英

保存到文件后,已编辑的XML内容不会更改

[英]Edited XML content not changing after save to File

我正在解析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();

您正在更新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();
        }
    }
}

暂无
暂无

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

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