繁体   English   中英

使用JSoup在Java中修改html标记自身的文本

[英]Modifying an html tag's own text in Java using JSoup

是的,假设我有这段HT​​ML

<p>And finally, how about some <a href="http://www.yahoo.com/">Links?</a></p>

我只想访问和修改“最后,关于某些内容”部分,并获得以下信息:

<p>new text <a href="http://www.yahoo.com/">Links?</a></p>

我似乎不知道如何。 到目前为止,这是我尝试过的方法:

Document doc = null;
    try {
        doc = Jsoup.connect("http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html").userAgent("Mozilla").get();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
Elements d = doc.body().children();
Element e = d.get(20); //Assuming the HTML line in question is found at index 20
e.text("new text") //just outputs <p>new value</p>, which is not good for me

看来我可以通过

Element e = d.get(20);
System.out.println("\n"+e.ownText()); //outputs: And finally, how about some

但是修改它不起作用。

Element e = d.get(20);
String s = e.toString().replace(e.ownText(), "new text");
e.text(s);
System.out.println(e.toString());

上面代码的输出是

<p>&lt;p&gt;changed &lt;a href=&quot;http://www.yahoo.com/&quot;&gt;Links?&lt;/a&gt;&lt;/p&gt;</p>

似乎将标记用作文字,但是我希望将其用作<或>,因为然后必须使用新文本重新构建网页。

任何帮助将不胜感激。

怎么样

Element e = d.get(20);
e.text("new text"); 
e.append("<a href=\"http://www.yahoo.com/\">Links?</a>");//lets you add HTML.

如果链接是动态的,并且您不想更改它,则可以先存储它,然后再使用

Element e = d.get(20);
Element link = e.child(0);
e.text("new text"); 
e.append(link.toString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM