Fatih Türkeri
Fatih Türkeri

Reputation: 89

how to use <,> tags in java when create xml file

I want to html tag in xml. I'm using CDATA it is run in xml but I create xml file with java <, > tags was "<". I don't understand this situation.

String returnUrl="<![CDATA[ac=S<br/>DNbZCQOijAl6HrAAyyGV]]>";
Node returnUrlNode = doc.createElement("returnurl");
returnUrlNode.setTextContent(returnUrl);
userNode.appendChild(returnUrlNode);

Upvotes: 2

Views: 482

Answers (3)

Xenoveritas
Xenoveritas

Reputation: 76

If for whatever reason you want the text to be in a CDATA section and not a simple text node, you'll need to create the CDATA yourself. I'm assuming you're using the DOM and not some API that looks similar, so it would be:

Node returnUrlNode = doc.createElement("returnurl");
returnUrlNode.appendChild(
    doc.createCDATASection(
        "Whatever text you wanted to go in here, including unescaped < and >."));

Note that like SLaks pointed out, when the DOM is serialized, all escaping will happen automatically. (In this case, that means that the <![CDATA[ and ]]> will be added automatically.) This is just how you'd create an actual CDATA section if you need the output to be a CDATA section and not a normal text node.

Upvotes: 4

Dan
Dan

Reputation: 1018

You need to use the XML escape characters:

& &amp; 
< &lt; 
> &gt; 
" &quot; 
' &apos;

Upvotes: 1

SLaks
SLaks

Reputation: 887657

The Java XML APIs will automatically escape your content.

You can just write .setTextContent("ac=S<br/>DNbZCQOijAl6HrAAyyGV"), and Java will excape the < and > for you.

Upvotes: 3

Related Questions