java - 如何在解析 XML 并将它们作为新 XML 文件写回时保留转义字符,如 "或 &lt 或 &gt

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

请帮我解决这个问题。提前谢谢你。

最佳答案

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

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

关于java - 如何在解析 XML 并将它们作为新 XML 文件写回时保留转义字符,如 "或 &lt 或 &gt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28621854/

相关文章:

Java套接字使用wireshark获取数据包

xml-parsing - bison/flex 中的简单 XML 解析器

java - 为什么我的 XPath 没有选择任何东西?

c++ - Libxml2 xmlSchemaParse 失败

python - 使用 xml.etree.ElementTree 获取子节点的所有实例

java - json 转 xml java

java - 如何在 querydsl 中使用别名?

ios - 如何在 ios 中使用 Storyboard解析 Xml 数据?

Java,如何有效地对大型输入流进行分块?

java - 如何在 Spring Boot 的每个请求中获取当前用户?