java - Java DOM Transformer - XML 创建不会替换最终 xml 中的撇号和引号
问题描述
我正在尝试创建一个 XML 并根据输入将其作为对调用者的响应返回。
对于大多数部分,转换器按预期工作,但它不会将撇号和引号转换为它们的 XML 等效项。下面是我正在使用的代码
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("template");
doc.appendChild(rootElement);
/* Adding attendant ID */
Element line = doc.createElement("line");
line.appendChild(doc.createTextNode("----&----<------>------'-----\"--------"));
Attr Attr1 = doc.createAttribute("Attr1");
Attr1.setValue("attribute value 1");
line.setAttributeNode(Attr1);
Attr Attr2 = doc.createAttribute("Attr2");
Attr2.setValue("attribute value 2");
line.setAttributeNode(Attr2);
rootElement.appendChild(line);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
// Output to String
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String strResult = writer.toString();
//return escapeXml(strResult);
System.out.println(strResult);
结果输出
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<template>
<line Attr1="attribute value 1" Attr2="attribute value 2">----&----<------>------'-----"--------</line>
</template>
预期结果
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<template>
<line Attr1="attribute value 1" Attr2="attribute value 2">----&----<------>------'-----"--------</line>
</template>
最初我认为可以在将这些字符作为输入发送到转换器之前将其转义,但它会将所有与符号替换为等效的"&"
. 如果在创建最终 XML 后替换撇号或引号,它也会替换属性。
我想我们可以通过两种方式解决这个问题
- 我可以
& , < , > , ' , "
在添加到节点之前转换它,而转换器会忽略它 - 明确指示转换器将
' , "
它们转换为等效的 XML。
目前我不知道如何实现这些。有人可以帮助我吗,或者如果有更好的解决方案来创建有效的 XML,将不胜感激。
谢谢。
解决方案
为什么要转义引号和撇号?XML 不要求对它们进行转义(除非在它们与属性分隔符冲突的属性中)。序列化程序知道它在做什么:相信它。
推荐阅读
- javascript - 我无法比较 Javascript 中的两个数组项
- excel - 如何从 Excel 中的单元格中删除某些文本?
- eclipse - 我所有的 Eclipse 文件都显示为 .DATAWAIT
- c# - 我应该处置不属于自己的实例吗?
- winforms - WInform DataGridView 到 Datetimepicker C#
- android - 如何在 Firebase 中显示示例(3 和 7)之间的类别?
- postgresql - 当数据库位于同一 postgres 服务器中时,如何查询两个 postgres 数据库(使用单个查询)?
- angularjs - 使用 ngModel 将 AngularJS 指令升级为 Angular 组件
- spring-webflux - 如何使用 Spring Webflux 创建列表流?
- google-play - Google Play 上的应用提供的订阅产品是否可以在任何地方公开显示?