2012-03-22 2 views
3

내 HTML 문서에서이 구조를 가지고 :랩 일반 HTML 텍스트 주위에 태그

<p> 
"<em>You</em> began the evening well, Charlotte," said Mrs.&nbsp;Bennet with civil   self–command to Miss Lucas. "<em>You</em> were Mr.&nbsp;Bingley's first choice." 
</p> 

을하지만 난 그것을 처리 할 수 ​​있도록, 내 "일반 텍스트"를 태그 wrappted해야 :)

<p> 
    <text>"</text> 
    <em>You</em> 
    <text> began the evening well, Charlotte," said Mrs.&nbsp;Bennet with civil self–command to Miss Lucas. "</text> 
    <em>You</em> 
    <text> were Mr.&nbsp;Bingley's first choice."</text> 
</p> 

아이디어가 있습니까? tagsoup와 jsoup를 보았습니다.하지만이 문제를 쉽게 해결할 수있는 방법은 없습니다. 아마도 멋진 정규 표현식을 사용했을 것입니다.

public static Node toTextElement(String str) { 
    Element e = new Element(Tag.valueOf("text"), ""); 
    e.appendText(str); 
    return e; 
} 

public static void replaceTextNodes(Node root) { 
    if (root instanceof TextNode) 
     root.replaceWith(toTextElement(((TextNode) root).text())); 
    else 
     for (Node child : root.childNodes()) 
      replaceTextNodes(child); 
} 

테스트 코드 :

감사

답변

5

여기 제안입니다

String html = "<p>\"<em>You</em> began the evening well, Charlotte,\" " + 
     "said Mrs.&nbsp;Bennet with civil self–command to Miss Lucas." + 
     " \"<em>You</em> were Mr.&nbsp;Bingley's first choice.\"</p>"; 

Document doc = Jsoup.parse(html); 

for (Node n : doc.body().children()) 
    replaceTextNodes(n); 

System.out.println(doc); 

출력 :

완벽하게
<html> 
<head></head> 
<body> 
    <p> 
    <text> 
    &quot; 
    </text><em> 
    <text> 
    You 
    </text></em> 
    <text> 
    began the evening well, Charlotte,&quot; said Mrs.&nbsp;Bennet with civil self–command to Miss Lucas. &quot; 
    </text><em> 
    <text> 
    You 
    </text></em> 
    <text> 
    were Mr.&nbsp;Bingley's first choice.&quot; 
    </text></p> 
</body> 
</html> 
+0

작품! 감사! 실제로 페인트를 사용하여 캔버스에 html을 렌더링하고 텍스트 메소드를 그릴 때 이것을 사용하려고합니다. 이것은 시작하는 좋은 방법입니까? :) – Richard