Parser JSoup将标记更改为小写字母

时间:2013-10-29 18:23:33

标签: java jsoup

我做了一些研究,似乎标准Jsoup做了这个改变。我想知道是否有办法配置这个或者是否有其他的Parser我可以转换为Jsoup的文档,或者某种方法来解决这个问题?

5 个答案:

答案 0 :(得分:7)

不幸的是,Tag类的构造函数将名称更改为小写:

private Tag(String tagName) {
    this.tagName = tagName.toLowerCase();
}

但是有两种方法可以改变这种行为:

  1. 如果您需要 clean 解决方案,可以克隆/下载JSoup Git并更改此行。
  2. 如果您想要解决方案,可以使用反射。
  3. #2的示例:

    Field tagName = Tag.class.getDeclaredField("tagName"); // Get the field which contains the tagname
    tagName.setAccessible(true); // Set accessible to allow changes
    
    for( Element element : doc.select("*") ) // Iterate over all tags
    {
        Tag tag = element.tag(); // Get the tag of the element
        String value = tagName.get(tag).toString(); // Get the value (= name) of the tag
    
        if( !value.startsWith("#") ) // You can ignore all tags starting with a '#'
        {
            tagName.set(tag, value.toUpperCase()); // Set the tagname to the uppercase
        }
    }
    
    tagName.setAccessible(false); // Revert to false
    

答案 1 :(得分:1)

版本1.9.3中引入了ParseSettings类。 它附带了保留标签和属性的大小写的选项。

答案 2 :(得分:1)

以下是代码示例(版本> = 1.11.x):

Parser parser = Parser.htmlParser();
parser.settings(new ParseSettings(true, true));
Document doc = parser.parseInput(html, baseUrl);

答案 3 :(得分:1)

您必须使用xmlParser而不是htmlParser,并且标记将保持不变。一行就能解决问题:

String html = "<camelCaseTag>some text</camelCaseTag>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());

答案 4 :(得分:0)

我使用的是没有这段代码的1.11.1-SNAPSHOT版本。

private Tag(String tagName) {
    this.tagName = tagName.toLowerCase();
}

所以我按照上面的建议检查了ParseSettings并更改了以下代码:

static {
    htmlDefault = new ParseSettings(false, false);
    preserveCase = new ParseSettings(true, true);
}

为:

static {
    htmlDefault = new ParseSettings(true, true);
    preserveCase = new ParseSettings(true, true);
}

并在构建JAR时跳过了测试用例。

相关问题