Jsoup如何输出格式良好的XML?

pet*_*ust 6 html xml jsoup

当Jsoup遇到某些类型的HTML(复杂或不正确)时,它可能会发出格式错误的HTML.一个例子是:

<html>
 <head>
  <meta name="x" content="y is "bad" here">
 </head>
 <body/>
</html>
Run Code Online (Sandbox Code Playgroud)

引号应该被转义的地方.当Jsoup解析它时,它会发出:

<html>
 <head>
  <meta name="x" content="y is " bad"="" here"="" />
 </head>
 <body></body>
</html>
Run Code Online (Sandbox Code Playgroud)

这不符合HTML或XML.这是有问题的,因为它将在链的下一个解析器中失败.

有没有办法确保Jsoup发出错误消息或(如HtmlTidy)可以输出格式良好的XML,即使它已经丢失了一些信息(毕竟我们现在无法确定什么是正确的).

更新:失败的代码是:

    @Test
public void testJsoupParseMetaBad() {
    String s = "<html><meta name=\"x\" content=\"y is \"bad\" here\"><body></html>";
    Document doc = Jsoup.parse(s);
    String ss = doc.toString();
        Assert.assertEquals("<html> <head> <meta name=\"x\" content=\"y is \""
            +" bad\"=\"\" here\"=\"\" /> </head> <body></body> </html>", ss);
}
Run Code Online (Sandbox Code Playgroud)

我在用:

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

其他人似乎有同样的问题: JSoup - 内部属性引用答案那里没有帮助我,因为我必须接受我给予的

use*_*883 1

问题是当你解析时,因为 jsoup 正在创建 3 个属性:

content="y is "bad" here" 
Run Code Online (Sandbox Code Playgroud)

并且属性的名称包含 quote " 字符。Jsoup 会转义属性的值,但不会转义其名称。

由于您正在从字符串构建 html 文档,因此您可能会在解析阶段出现错误。有一种方法获取 org.jsoup.parser.Parser 作为参数。默认解析方法不跟踪错误。

    String s = "<html><meta name=\"x\" content=\"y is \"bad\" here\"><body></html>";
    Parser parser = Parser.htmlParser(); // or Parser.xmlParser
    parser.setTrackErrors(100);
    Document doc = Jsoup.parse(s, "", parser);
    System.out.println(parser.getErrors());
Run Code Online (Sandbox Code Playgroud)

输出:

[37:输入状态 [AfterAttributeValue_quoted] 中出现意外字符 'a',40:输入状态 [AttributeName] 中出现意外字符 ' ',46:输入状态 [AttributeName] 中出现意外字符 '>']

如果您不想更改解析而只想获得有效的输出,您可以删除无效的属性:

public static void fixIt(Document doc) {
    Elements els = doc.getAllElements();
    for(Element el:els){
        Attributes attributes = el.attributes();
        Set<String> remove = new HashSet<>();
        for(Attribute a:attributes){
            if(isForbidden(a.getKey())){
               remove.add(a.getKey());
            }
        }

        for(String k:remove){
            el.removeAttr(k);
        }
    }
}

public static boolean isForbidden(String el) {
    return el.contains("\""); //TODO
}
Run Code Online (Sandbox Code Playgroud)