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

Wil*_*iro 7 java jsoup

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

oll*_*llo 7

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

private Tag(String tagName) {
    this.tagName = tagName.toLowerCase();
}
Run Code Online (Sandbox Code Playgroud)

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

  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
Run Code Online (Sandbox Code Playgroud)


Inv*_*tor 6

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

Parser parser = Parser.htmlParser();
parser.settings(new ParseSettings(true, true));
Document doc = parser.parseInput(html, baseUrl);
Run Code Online (Sandbox Code Playgroud)