Bibin Mathew
Bibin Mathew

Reputation: 213

Displaying Difference of an XML file in HTML format

I am working on this code to show the differences in two files in an HTML format .I am doing it in Java . This is what i have done so far . 1. I am reading the file contents into String Arrays . 2. Using LCS algorithm to find the longest sub sequence matrix mentioned here 3. Use a string builder to create Html head 4. Using the LCS matrix , append the strings to the string buffer. 5. if there is a difference in two strings i change the tr bgcolour to show it in a different color.

This works perfectly fine when i use a normal text file .

code snippet :

        sb.append("<tr bgcolor='#FF0000'>");
        sb.append("<td>");
        sb.append( x[i++]);
        sb.append("</td>");
        sb.append("<td>");
        sb.append( y[j++]);
        sb.append("</td>");
        sb.append("</tr>");

But Now if i do a diff between two Xml files i am not able to see the contents.

If the text is normal , the HTML formed is :

 <td>normaltext</td>

//rendered properly

if the xml files contains

<Hello>

tag the html formed contains

<td><Hello></td>

because of which browser is not able to render it properly.

How can i resolve it ? Any pointers will be helpful.

Upvotes: 0

Views: 50

Answers (1)

libik
libik

Reputation: 23029

replace < by &lt; and > by &gt;

Problem solved.


To be more concrete in your case, just do the following :

    sb.append("<tr bgcolor='#FF0000'>");
    sb.append("<td>");
    sb.append( x[i++].replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
    sb.append("</td>");
    sb.append("<td>");
    sb.append( y[j++].replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
    sb.append("</td>");
    sb.append("</tr>");

According to the comment, this would be even better :

    sb.append("<tr bgcolor='#FF0000'>");
    sb.append("<td>");
    sb.append( x[i++].replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
    sb.append("</td>");
    sb.append("<td>");
    sb.append( y[j++].replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
    sb.append("</td>");
    sb.append("</tr>");

To have <= and >= not replaced, this is working solution, but it is a little nasty :) :

    String x = "<Hello>&<=<blabbalal>";
    System.out.println(x.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("&gt;=", ">=").replaceAll("&lt;=", "<="));

Has this output :

&lt;Hello&gt;&amp;<=&lt;blabbalal&gt;

Upvotes: 1

Related Questions