【问题标题】:Parser JSoup change the tags to lower case letterParser JSoup 将标签更改为小写字母
【发布时间】:2013-10-29 18:23:33
【问题描述】:

我做了一些研究,似乎是标准的 Jsoup 进行此更改。我想知道是否有办法对此进行配置,或者是否有其他解析器可以转换为 Jsoup 的文档,或者有什么方法可以解决这个问题?

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    很遗憾没有,Tag类的构造函数把名字改成了小写:

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

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

    1. 如果您想要干净 解决方案,您可以克隆/下载JSoup Git 并更改此行。
    2. 如果你想要一个解决方案,你可以使用反射。

    #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 真的这么努力吗?我以为只是要更改的那一行。
    • 因为我不只使用解析器,我使用其他功能。如果需要,我可以在某个地方发布 de change libray....
    • 您必须更改的类的名称会很棒:-) ...仅出于个人兴趣。
    • 已尝试解决方案 1。不起作用。还有哪些类需要修改知道吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这是一个代码示例(版本 >= 1.11.x):

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

      【讨论】:

        【解决方案4】:

        您必须使用 xmlParser 而不是 htmlParser,并且标签将保持不变。一行就可以了:

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

        【讨论】:

          【解决方案5】:

          我使用的是 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 时跳过了测试用例。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-08-23
            • 1970-01-01
            • 1970-01-01
            • 2017-10-26
            • 1970-01-01
            • 2016-06-22
            • 1970-01-01
            • 2018-09-15
            相关资源
            最近更新 更多