JSoup似乎忽略了字符代码?

时间:2016-03-10 21:23:02

标签: java html regex arraylist jsoup

我在Java中构建一个类似CMS的小型应用程序,它接受带有衬衫名称/描述的.txt文件,并将名称/描述加载到customShirts的ArrayList中(我制作的小类)。然后,它遍历ArrayList,并使用JSoup解析模板(template.html)并将衬衫的独特细节插入HTML。最后,它将每件衬衫抽出到输出文件夹中的HTML文件中。

当描述加载到customShirts的ArrayList中时,我用适当的字符代码替换所有特殊字符,以便正确显示它们(例如,用'替换撇号)。问题是,我注意到JSoup似乎会自动将字符代码转换为实际字符,这是一个问题,因为我需要输出可显示(需要字符代码)。有什么办法可以解决这个问题吗?我已经查看了其他解决方法,例如:Jsoup unescapes special characters,但是他们似乎需要在插入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!");

    }

}

提前致谢!

1 个答案:

答案 0 :(得分:3)

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

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

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

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

为了确保所有Unicode特殊字符都是HTML编码的。

对于必须将数据填入HTML文件的大型项目,您可以查看使用Thymeleaf等模板引擎 - 它更易于用于此类工作(代码更少和这样),它提供了更多专门用于此过程的功能。对于小型项目(如你的),Jsoup很好(过去我曾经这样使用它),但是对于更大(甚至更小)的项目,你会想要研究一些更专业的工具。