2015-01-01 1 views
3

body 태그 다음에 생성 된 html에 <div class="wrapper">을 추가하려고합니다. 결말 </div>은 결말 앞에 있어야합니다. 지금까지 나는JSoup 본문 뒤에 래퍼 div를 추가합니다.

private String addWrapper(String html) { 
    Document doc = Jsoup.parse(html); 
    Element e = doc.select("body").first().appendElement("div"); 
    e.attr("class", "wrapper"); 

    return doc.toString(); 
} 

을 가지고 내가 너무 HTML에서 "</머리 >"를 얻고 이유도 알아낼 수 없습니다

</head> 
    <body> 
    &lt;/head&gt; 
    <p>Heyo</p> 
    <div class="wrapper"></div> 
</body> 
</html> 

을 얻고있다. 나는 JSoup를 사용할 때만 그것을 얻는다.

답변

4

Jsoup Document는 normalize 메서드로 텍스트를 표준화합니다. The method is here in Document class. 그래서 태그와 함께 감 쌉니다.

Jsoup.parse() 메소드에서는 3 개의 매개 변수 parse (String html, String baseUri, Parser parser)를 사용할 수 있습니다.

파서 매개 변수에 XMLTreeBuilder를 사용하는 Parser.xmlParser를 지정합니다. 그렇지 않으면 HtmlTreeBuilder를 사용하고 html을 정규화합니다.

String html = "<body>&lt;/head&gt;<p>Heyo</p></body>"; 

    Document doc = Jsoup.parse(html, "", Parser.xmlParser()); 

    Attributes attributes = new Attributes(); 
    attributes.put("class","wrapper"); 

    Element e = new Element(Tag.valueOf("div"), "", attributes); 
    e.html(doc.select("body").html()); 

    doc.select("body").html(e.toString()); 

    System.out.println(doc.toString()); 
+0

이 일을 그! :

나는 최신 코드 (이 최적화 될 수있다), 시도 고맙습니다!! – CodeMinion

관련 문제