【问题标题】:Edited XML content not changing after save to File保存到文件后编辑的 XML 内容未更改
【发布时间】:2016-06-03 14:09:29
【问题描述】:

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

【问题讨论】:

    标签: java xml dom xml-parsing


    【解决方案1】:

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

    【讨论】:

    • 感谢您的强大方法,将使用它。那么我如何才能使这些更改反映在 doc 对象上呢?
    • child.setTextContent 给出错误,因为 setTextContent 不是 Node 的方法 :(
    • nvm,我用 setNodeValue() 替换了方法,一切正常。你救了我:)
    猜你喜欢
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2015-01-13
    • 2023-03-28
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多