0

I have a simple servlet application that sends XML response to JavaScript. When I check in my Firebug, This resposonse is received by JavaScript as

<valid> AT&T,0.51851370625875,0.97944711419669,Verizon,0.47641942539114,0.99005717081381,wifi,0.48596657869633,0.88912486160201 </valid>

Which is a perfectly valid XML response - but Firebug also shows XML error

XML Parsing Error: not well-formed Location: moz-nullprincipal:{30f70c51-7f01-48b4-9f69-4f0093e02ba6} Line Number 1, Column 12:
<valid>AT&T,0.51851370625875,0.97944711419669,Verizon,0.47641942539114,0.9900571...

It shows the error at the first comma - which does not makes sense at all. I even tried replacing commas with spaces - but even that gives same problem.

I generate my response from Servlet by

String ret="";

for (int i=0; i < ping.size(); i++)
{

    ret += ping.get(i) ;
    if(i != ping.size()-1){
        ret += ",";
    }                   
}

response.setContentType("text/xml");           
response.setHeader("Cache-Control", "no-cache");

response.getWriter().write("<valid>"+ret+"</valid>");

And in my JavaScript, I try to retrieve data as

var message = xmlHttp.responseXML.getElementsByTagName("valid")[0].childNodes[0].nodeValue;

I have use this exact same approach before - not sure why is this not working anymore. All I need to do is store the values (AT&T,0.51851370625875,0.97944711419669,Verizon,0.47641942539114,0.99005717081381,wifi,0.48596657869633,0.88912486160201) in a javascript array.

Any ideas?

1
  • Please indent code with four spaces, as it says in the help section. Commented May 18, 2011 at 1:59

2 Answers 2

2

The issue is the & in AT&T. You have to escape out that character not the comma.

The reason you get the error at the first comma is that it's trying to parse &T as an html character.

The replace should be &#38; for an ampersand

Sign up to request clarification or add additional context in comments.

Comments

0

As said, this isn't valid XML. The & is a special character in XML.

You want to use Apache Commons Lang StringEscapeUtils#escapeXml() to escape special characters in XML. First download commons-lang-2.6.jar, drop it in /WEB-INF/lib folder and replace the last line of your servlet as follows:

response.getWriter().write("<valid>" + StringEscapeUtils.escapeXml(ret) + "</valid>");

Unrelated to the concrete problem, your String concatenation loop with += is pretty inefficient. Consider using StringBuilder instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.