首页 > 解决方案 > 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">----&amp;----&lt;------&gt;------'-----"--------</line>
</template>

预期结果

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<template>
    <line Attr1="attribute value 1" Attr2="attribute value 2">----&amp;----&lt;------&gt;------&apos;-----&quot;--------</line>
</template>

最初我认为可以在将这些字符作为输入发送到转换器之前将其转义,但它会将所有与符号替换为等效的"&amp;". 如果在创建最终 XML 后替换撇号或引号,它也会替换属性。

我想我们可以通过两种方式解决这个问题

  1. 我可以& , < , > , ' , "在添加到节点之前转换它,而转换器会忽略它
  2. 明确指示转换器将' , "它们转换为等效的 XML。

目前我不知道如何实现这些。有人可以帮助我吗,或者如果有更好的解决方案来创建有效的 XML,将不胜感激。

谢谢。

标签: javaxml

解决方案


为什么要转义引号和撇号?XML 不要求对它们进行转义(除非在它们与属性分隔符冲突的属性中)。序列化程序知道它在做什么:相信它。


推荐阅读