jsoup在链接href中转义&符号

时间:2013-08-15 18:57:41

标签: jsoup

JSoup在链接href中转义URL的查询部分中的&符号。鉴于下面的样本

    String l_input = "<html><body>before <a href=\"http://a.b.com/ct.html\">link text</a> after</body></html>";
    org.jsoup.nodes.Document l_doc = org.jsoup.Jsoup.parse(l_input);
    org.jsoup.select.Elements l_html_links = l_doc.getElementsByTag("a");
    for (org.jsoup.nodes.Element l : l_html_links) {
      l.attr("href", "http://a.b.com/ct.html?a=111&b=222");
    }
    String l_output = l_doc.outerHtml();

输出

    <html>
    <head></head>
    <body>
    before 
    <a href="http://a.b.com/ct.html?a=111&amp;b=222">link text</a> after
    </body>
    </html>

单身&amp;被转移到&amp; amp; 。不应该留下来作为&amp; ?

2 个答案:

答案 0 :(得分:5)

看来你做不到。我经历了源​​头,找到了逃生发生的地方。

它在Attribute.java

中定义
/**
 Get the HTML representation of this attribute; e.g. {@code href="index.html"}.
 @return HTML
 */
public String html() {
    return key + "=\"" + Entities.escape(value, (new Document("")).outputSettings()) + "\"";
}

你看到它正在使用Entities.java jsoup采用new document("");的默认输出设置。这样你就无法覆盖这些设置。

也许你应该发布一个功能请求。

Btw:默认的转义模式设置为base

Documet.java创建默认的OutputSettings个对象,并定义there。参见:

/**
 * A HTML Document.
 *
 * @author Jonathan Hedley, jonathan@hedley.net 
 */
public class Document extends Element {
    private OutputSettings outputSettings = new OutputSettings();
    // ...
}


/**
 * A Document's output settings control the form of the text() and html() methods.
 */
public static class OutputSettings implements Cloneable {
    private Entities.EscapeMode escapeMode = Entities.EscapeMode.base;
    // ...
}

解决方法(unescape as XML):

使用apache commons lang项目中的StringEscapeUtils,您可以轻松逃脱这些想法。参见:

    String unescapedXml = StringEscapeUtils.unescapeXml(l_output);
    System.out.println(unescapedXml);

这将打印:

<html>
 <head></head>
 <body>
  before 
  <a href="http://a.b.com/ct.html?a=111&b=222">link text</a> after
 </body>
</html>

但当然,它会取代所有&amp; ...

答案 1 :(得分:1)

Jsoup做什么实际上是写网址的正确方法。例如。如果你写“id = 1&amp; copy = true”浏览器可能会将其解释为“id = 1©= true”。所以你必须改变它。

我是从https://groups.google.com/forum/#!topic/jsoup/eK4XxHc4Tro

得到的
相关问题