2015-05-24 19 views
2

的每一个标签,我有以下的HTML:使用Jsoup库中的每一个标签我怎么能代替“文本”中使用Jsoup

<html> 
<head> 
</head> 
<body> 
    <div id="content" > 
     <p>text <strong>text</strong> text <em>text</em> text </p> 
    </div> 
</body>  
</html> 

我怎么能代替“文”到“字”。 我想看:

<html> 
<head> 
</head> 
<body> 
    <div id="content" > 
     <p>word <strong>word</strong> word <em>word</em> word </p> 
    </div> 
</body>  
</html> 

谢谢你的任何建议!

UPD: 谢谢你的回答,但我发现通用的方法:

Element entry = doc.select("div").first(); 
    Elements tags = entry.getAllElements(); 
    for (Element tag : tags) { 
     for (Node child : tag.childNodes()) { 
      if (child instanceof TextNode && !((TextNode) child).isBlank()) { 
       System.out.println(child); //text 
       ((TextNode) child).text("word"); //replace to word 
      } 
     } 
    } 

回答

1

快速搜索打开了这个代码:

Elements strongs = doc.select("strong"); 
Element f = strongs.first(); 
Element l = strongs.last();1,siblings.lastIndexOf(l)); 

首先你想要做的就是了解库的工作原理以及它包含的功能,然后弄清楚如何使用库努力去做你需要的。上面的代码似乎允许你选择一个强大的元素,在这一点你可以更新它的内部文本,但我相信有很多方法可以实现相同。

通常,解析xml的大多数库都能够选择文档对象模型中的任何给定元素或任何元素列表,并且可以操作元素本身或其内部文本,属性等。

一旦您获得了使用不同库的更多经验,您的出发点就是查找库的文档以查看该库的功能。如果你看到一个方法说明它做了什么,那就是它的作用,你可以期望用它来实现这个目标。然后,而不是写一个关于堆栈溢出的问题,你只需要解析你正在使用的库的功能,并找出如何使用它来做你想做的事情。

2
Document doc = Jsoup.connect(url).get(); 
String str = doc.toString(); 
str = str.replace("text", "word"); 

尝试它..

0
String html = "<html> ..."; 
    Document doc = Jsoup.parse(html); 
    Elements p = doc.select("div#content > p"); 
    p.html(p.html().replaceAll("text", "word")); 
    System.out.println(doc.toString()); 

div#content > p意味着在元件<div>该id为content元素<p>

如果你想只在<strong>text</strong>替换文本:

Elements p = doc.select("div#content > p > strong"); 
    p.html(p.html().replaceAll("text", "word"));