Java 如何告诉Xalan转义HTML属性中的字符

Java 如何告诉Xalan转义HTML属性中的字符,java,xml-serialization,xalan,Java,Xml Serialization,Xalan,下面Java代码的结果是 <input value="<http://example.org/>"> 我想要的是 <input value="&lt;http://example.org/&gt;"> 代码是 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element input = doc.creat

下面Java代码的结果是

<input value="<http://example.org/>">

我想要的是

<input value="&lt;http://example.org/&gt;">

代码是

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element input = doc.createElement("input");
input.setAttribute("value", "<http://example.org/>");

Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.INDENT, "yes");
xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.setOutputProperty(OutputKeys.ENCODING, "utf-8");
xform.setOutputProperty(OutputKeys.METHOD, "html");
StringWriter writer = new StringWriter();
xform.transform(new DOMSource(input), new StreamResult(writer));
System.out.println(writer.toString());
Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
元素输入=doc.createElement(“输入”);
input.setAttribute(“值”,“值”);
Transformer xform=TransformerFactory.newInstance().newTransformer();
setOutputProperty(OutputKeys.INDENT,“是”);
xform.setOutputProperty(“{http://xml.apache.org/xslt}缩进金额,“4”);
setOutputProperty(OutputKeys.OMIT_XML_声明,“yes”);
setOutputProperty(OutputKeys.ENCODING,“utf-8”);
setOutputProperty(OutputKeys.METHOD,“html”);
StringWriter编写器=新的StringWriter();
transform(新的DOMSource(输入),新的StreamResult(writer));
System.out.println(writer.toString());
xform的实现是com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl

Xalan是否有正确转义<和>字符的设置?它会导致ajax调用的客户端出现问题。

Apache Commons有a和a.unescapeXml()方法,您可以使用这些方法在将xml片段设置为属性之前对其进行转义

input.setAttribute("value", StringEscapeUtils.escapeXml("<http://example.org/>"));
input.setAttribute(“值”,StringEscapeUtils.escapeXml(“”);

希望大家帮忙,好好享受

我感觉将输出方法设置为“html”与此有关。我敢打赌,如果将其设置为“xml”,则不会发生这种情况。这种感觉是正确的,但我不能将其设置为“xml”,因为结果会在jQuery加载请求中以HTML形式发送回客户端。那么这是Xalan中的一个bug吗?我认为如果您告诉它生成XML,它将是一个bug。因为它被要求生成HTML,所以它所做的似乎不是一个bug。它是有效的HTML,只是不是有效的XML。谷歌搜索表明它也有一个“xhtml”输出方法,你试过了吗?可能是@ChamikaSandamal的复制品,我不这么认为。您链接的帖子是关于解决jQuery错误的,这篇帖子是关于让Xalan生成有效的x(ht)ml。ISTM您链接的帖子需要以“do x to get jQuery to do Y”的形式给出答案,其中这篇帖子需要以“do x to get Xalan to do Y”的形式给出答案。