JSoup 似乎忽略了字符代码?

JSoup seems to ignore character codes?

我正在 Java 中构建一个类似于 CMS 的小型应用程序,它使用带有衬衫 names/descriptions 的 .txt 文件并将 names/descriptions 加载到 customShirts 的 ArrayList(小class 我做了)。然后,它遍历 ArrayList,并使用 JSoup 解析模板 (template.html) 并将衬衫的独特细节插入到 HTML 中。最后,它将每件衬衫抽出到输出文件夹中自己的 HTML 文件中。

当描述加载到 customShirts 的 ArrayList 时,我将所有特殊字符替换为适当的字符代码,以便它们可以正确显示(例如,将撇号替换为 ')。问题是,我注意到 JSoup 似乎会自动将字符代码转换为实际字符,这是一个问题,因为我需要输出可显示(这需要字符代码)。我能做些什么来解决这个问题吗?我查看了其他解决方法,例如:,但它们似乎需要在使用 replaceAll 插入之前解析文件,并且我使用 JSoup 插入了字符代码敏感文本,这似乎并没有做到这一点一个选项。

下面是我制作的 HTML 生成器的代码:

public void generateShirtHTML(){

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

        File input = new File("html/template/template.html");
        Document doc = null;
        try {
            doc = Jsoup.parse(input, "UTF-8", "");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }

        Element title = doc.select("title").first();
        title.append(arrShirts.get(i).nameToCapitalized());

        Element headingTitle = doc.select("h1#headingTitle").first();
        headingTitle.html(arrShirts.get(i).nameToCapitalized());

        Element shirtDisplay = doc.select("p#alt1").first();
        shirtDisplay.html(arrShirts.get(i).name);

        Element descriptionBox = doc.select("div#descriptionbox p").first();
        descriptionBox.html(arrShirts.get(i).desc);
        System.out.println(arrShirts.get(i).desc);

        PrintWriter output;
        try {
            output = new PrintWriter("html/output/" + arrShirts.get(i).URL);
            output.println(doc.outerHtml());
            //System.out.println(doc.outerHtml());
            output.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Shirt " + i + " HTML generated!");

    }

}

提前致谢!

扩展一下我的评论(因为斯蒂芬鼓励我..),你可以使用

doc.outputSettings().escapeMode(Entities.EscapeMode.extended);

告诉 Jsoup 在输出中转义/编码特殊字符,例如。左双引号 () 为 &ldquo;。要使 Jsoup 编码 all 个特殊字符,您可能还需要添加

doc.outputSettings().charset("ASCII");

为了保证所有的Unicode特殊字符都会被HTML编码。

对于需要将数据填写到 HTML 文件中的大型项目,您可以考虑使用模板引擎,例如 Thymeleaf - 这种工作更容易使用(更少代码等),并且它提供了更多专门针对此过程的功能。对于小型项目(如您的项目),Jsoup 很好(我过去曾这样使用过),但对于更大(甚至更小)的项目,您需要研究一些更专业的工具。