2013-08-15 3 views
3

JSoup은 링크 href의 URL 쿼리 부분에서 앰퍼샌드를 이스케이프 처리합니다.링크 href의 앰퍼샌드를 이스케이프 처리하는 jsoup

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(); 

아래 주어진 샘플 출력은 단일 & & A가 탈출되는

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

이고; . &으로 머물러야하지 않습니까?

+0

에서이있어'및'유효한 기호 또는 유효한 XML과 XHTML 문서에 실패합니다. 따라서 모든 마크 업에서 표준화하기 위해 파싱해야합니다. – SRy

+0

SRy - 완전히 이해하고 있는지 확신 할 수 없습니다. URL의 고독한 앰퍼샌드가 유효하지 않으며 대신 이스케이프/엔티티 버전이어야한다고 말하고 있습니까? – Mitch

답변

4

그렇게 할 수없는 것 같습니다. 나는 출처를 지났고 탈출 한 곳을 발견했다.

는 그것은 거기 당신은 Entities.java jsoup가이 설정을 재정의 할 수 없습니다 방법입니다 new document("");의 기본 outputSettings 소요 사용 참조 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()) + "\""; 
} 

에 정의되어 있습니다.

아마도 기능 요청을 게시해야합니다.

Btw : 기본 이탈 모드는 base으로 설정됩니다.

Documet.java은 기본값 OutputSettings 개체를 만들고 there을 정의합니다. 참조 :

/** 
* A HTML Document. 
* 
* @author Jonathan Hedley, [email protected] 
*/ 
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; 
    // ... 
} 

해결 방법 (XML과 같은 언 이스케이프) 다음 StringEscapeUtils

apache commons lang 프로젝트에서 당신이 그가 easly 생각 벗어날 수 있습니다. 참조 :

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; ... Jsoup가 실제로 URL을 작성하는 올바른 방법입니다 무엇을

1

. 예 : "id = 1 & copy = true"라고 쓰면 브라우저가이를 "id = 1 © = true"로 해석 할 수 있습니다. 그래서 당신은 그것을 지적해야합니다.

내가 https://groups.google.com/forum/#!topic/jsoup/eK4XxHc4Tro

+0

올바르지 않습니다. 브라우저가 저작권 기호로 해석하고 복사하는 유일한 방법은 세미콜론으로 끝나는 경우입니다 : '© ='는 저작권 기호를 생성하지만'& copy ='는 사용하지 않습니다. – isapir

관련 문제