使用XML文檔時,我使用了已包含XML實體的字符串,並希望它們按原樣插入。但是,出現這種情況,而不是:使用javax.xml.transform.Transformer中的原始文本
String s = "This — That";
....
document.appendChild(document.createTextNode(s));
....
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
System.out.println(stringWriter.toString()); // outputs "This — That" at the relevant Node.
我有超過輸入字符串沒有控制,我需要精確地輸出「This — That
」。
如果我使用StringEscapeUtils.unescapeHtml
,輸出是「This — That
」,這不是我所需要的。
我也試過transformer.setOutputProperty(OutputKeys.ENCODING, "encoding")
的幾個版本,但還沒有找到一個編碼將「—
」轉換爲「—
」。
我該怎麼做才能防止javax.xml.transform.Transformer正確地重新轉義轉義的文本,或者如何轉換輸入以獲取輸出中的實體?
請解釋這是如何重複。
引用的問題有問題,「
 
」正在轉化爲CRLF,因爲這些實體正在得到解決。解決辦法是逃避實體。
我的問題是相反的。文本已經被轉義並且轉換器正在重新轉義文本。 「& mdash;」正在輸出「& amp; mdash」。
我無法使用該解決方案後轉換所有「&安培;」 - >「&」,因爲不是所有節點都代表html。
更完整代碼:
TransformerFactory factory = TransformerFactory.newInstance();
Transformer t = factory.newTransformer();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("Test");
rootElement.appendChild(document.createTextNode("This — That");
document.appendChild(rootElement);
DOMImplementation domImpl = bgDoc.getImplementation();
DocumentType docType = domImpl.createDocumentType("Test",
"-//Company//program//language",
"test.dtd");
t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
StringWriter writer = new StringWriter();
StreamResult rslt = new StreamResult(writer);
Source src = new DOMSource(document);
t.transform(src, rslt);
System.out.println(writer.toString());
// outputs xml header, then "<Test>This &mdash; That</Test>"
您需要將其解析爲XML而不是文本節點。 – SLaks
請您重新審查這個重複的狀態。 重複的問題是從String生成輸出。生成輸出解析實體,所以必須轉義。 我的問題是從String生成輸入。生成輸入轉義實體,所以s將獲得額外的轉義標記。 我的問題是不保留實體字符,如重複的問題。我保持足夠好。太好。我收到我不想要的演員。 – tzimnoch
'documentBuilder.parse'應該正是你想要的。 – SLaks