Justin R Justin R - 1 year ago 95
HTML Question

How to change ' ' to ' ' in HTML using JSoup

I am using JSoup to parse an HTML file and removing elements that aren't valid in XML because I need to apply XSLT to the file. The issue I am running into is the "nbsp;" that exist in my document. I need to change them to unicode '#160;' so that I can run the XSLT on the file.

So I want:

<p> &nbsp; </p>
<p> &nbsp; </p>
<p> &nbsp; </p>
<p> &nbsp; </p>

To Be:

<p> &#160; </p>
<p> &#160; </p>
<p> &#160; </p>
<p> &#160; </p>

I tried using a text replace but it didn't work:

Elements els = doc.body().getAllElements();
for (Element e : els) {
List<TextNode> tnList = e.textNodes();
for (TextNode tn : tnList){
String orig = tn.text();

Code that Performs the parsing:

File f = new File ("C:/Users/jrothst/Desktop/Test File.htm");

Document doc = Jsoup.parse(f, "UTF-8");
doc.outputSettings().syntax( Document.OutputSettings.Syntax.xml );
System.out.println("Starting parse..");

String html = doc.toString();
FileUtils.writeStringToFile(f, doc.outerHtml(), "UTF-8");

How can I make those changes happen using the JSoup libraries?

Answer Source

The following worked for me. You don't need to do any manual search and replace:

File f = new File ("C:/Users/seanbright/Desktop/Test File.htm");

Document doc = Jsoup.parse(f, "UTF-8");






(&#xa0; is the same thing as &#160; only in hexadecimal instead of decimal)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download