Java - convert named html entities to numbered xml entities

entities, html, java, parsing, xml

Solution

Have you tried with JTidy?

private String cleanData(String data) throws UnsupportedEncodingException {
    Tidy tidy = new Tidy();
    tidy.setInputEncoding("UTF-8");
    tidy.setOutputEncoding("UTF-8");
    tidy.setPrintBodyOnly(true); // only print the content
    tidy.setXmlOut(true); // to XML
    tidy.setSmartIndent(true); 
    ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes("UTF-8"));
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    tidy.parseDOM(inputStream, outputStream);
    return outputStream.toString("UTF-8");
}

Although I think it will repair some of your HTML code in case has something.

Problem

I'm looking to convert an html block that contains html named entities to an xml compliant block that uses numbered xml entities while leaving all html tag elements in place. This is the basic idea illustrated via test: ``` @Test public void testEvalHtmlEntitiesToXmlEntities() { String input = "<a href=\"test.html\">link&nbsp;</a>"; String expected = "<a href=\"test.html\">link&#160;</a>"; String actual = SomeUtil.eval(input); Assert.assertEquals(expected, actual); } ``` Is anyone aware of a Class that provides this functionality? I can write a regex to iterate through non element matches and do: ``` xlmString += StringEscapeUtils.escapeXml(StringEscapeUtils.unescapeHtml(htmlString)); ``` but hoped there is an easier way or a Class that already provides this.

Original source