如何在解析XML并将其作为新XML文件写回时保留转义字符,如“或<或>”

时间:2015-02-20 04:53:34

标签: java xml-parsing

以下是使用的代码,下面的元素内容被更改,这是替换转义字符

所不需要的
  <SelectionFilter>event.ProductType == &quot;CM_Media_Server&quot; and event.ProductVer == &quot;3.0.0.6&quot; and event.ProductPatch == &quot;0&quot;</SelectionFilter>

  <SelectionFilter>event.ProductType == "CM_Media_Server" and          event.ProductVer == "3.0.0.6" and event.ProductPatch == "0"</SelectionFilter>

以下是使用的代码,

         Document xmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(SourceXMLFile);
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression exprPre = xPath
                .compile("/SPIRITConfiguration/@Version");
        NodeList list = (NodeList) exprPre.evaluate(xmlDocument,
                XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i++) {
            list.item(i).setTextContent(ModelVersion.getValue());
        }

        // write the content back into new renamed xml file
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(xmlDocument);
        StreamResult result = new StreamResult(new File(DestxmlFile));
        transformer.transform(source, result);

请帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

DocumentBuilderFactory上,您可以调用setExpandEntityReferences方法关闭设置:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);
Document xmlDocument = factory.newDocumentBuilder().parse(SourceXMLFile);