Search code examples
javaxmlampersandtransformer-model

Java xml Transformer to escape &


I am having a problem with javax.xml.transform.Transformer.

I am trying to create a XML document and one of the attributes is HTTP link which contains & for query. After I've invoked the transform() method, all the & characters become &.

So is there any way that I can configure Transformer not to convert & to &? Thanks in advance.

Edit


In the xml document that I am trying to create, one of the attributes is a http link with query string. So what I would like to have as a result is something like

<Notification url="http://www.xyz.com/notify.jsp?param1=123&param2=345/>

But I am getting now is

<Notification url="http://www.xyz.com/notify.jsp?param1=123&amp;param2=345/>

Because I have to transform the xml document into a String and send it over socket. So I do not want & converted to &amp; as final result.


Solution

  • After I've invoked transform method, all the & characters become &amp;

    That's exactly what has to happen.

    What makes you assume that <div>A &amp; B</div> is correct XML/HTML and something like <div title="A &amp; B" /> is not?

    The & has to be escaped absolutely everywhere, that includes attribute values, such as href.