2012-03-22 5 views
3

У меня есть эта структура в моем HTML документе:Wrap тег вокруг обычного 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> 

Любые идеи, как это осуществить? Я посмотрел на tagoup и jsoup, но я не думаю, что это легко решить. Возможно, используя какое-то причудливое регулярное выражение.

Благодаря

ответ

5

Вот предложение:

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

Код испытания:

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

отлично работает! Благодаря! Im фактически пытается использовать это для рендеринга html на холсте с использованием красок и рисования текстовых методов. Это хороший способ начать? :) – Richard