【发布时间】:2013-10-29 18:23:33
【问题描述】:
我做了一些研究,似乎是标准的 Jsoup 进行此更改。我想知道是否有办法对此进行配置,或者是否有其他解析器可以转换为 Jsoup 的文档,或者有什么方法可以解决这个问题?
【问题讨论】:
我做了一些研究,似乎是标准的 Jsoup 进行此更改。我想知道是否有办法对此进行配置,或者是否有其他解析器可以转换为 Jsoup 的文档,或者有什么方法可以解决这个问题?
【问题讨论】:
很遗憾没有,Tag类的构造函数把名字改成了小写:
private Tag(String tagName) {
this.tagName = tagName.toLowerCase();
}
但是有两种方法可以改变这种行为:
#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.9.3 版本引入了 ParseSettings 类。 它带有为标签和属性保留大小写的选项。
【讨论】:
这是一个代码示例(版本 >= 1.11.x):
Parser parser = Parser.htmlParser();
parser.settings(new ParseSettings(true, true));
Document doc = parser.parseInput(html, baseUrl);
【讨论】:
您必须使用 xmlParser 而不是 htmlParser,并且标签将保持不变。一行就可以了:
String html = "<camelCaseTag>some text</camelCaseTag>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
【讨论】:
我使用的是 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 时跳过了测试用例。
【讨论】: