开发者

How do I replace an attribute using htmlParser?

UPDATE: Hi Pascal, Thanks for the quick reply, This is almost what I wanted. The newlink is different for each tag, can you please help me to do that.

All I need to do is iterate over all the link tags that appear in the input String, grab their value, and replace with a different link with out disturbing the link text

I am new using htmlParser in 开发者_Python百科Java, please help me with this condition.

htmlString =  <a class="user" href="">first name</a> posted on <a class="user" href="">Test Test</a>'s wiki entry, <a href="http://localhost:8080/b/lll/ddd">werwrwrwerwerwer</a>, in 

I need to replace the href link in <a class="user" href=""> to another link in the tag.


If you are using htmlparser as HTML parser, you can do some transformations with visitors.

For example, you could create your own NodeVisitor to visit a tags:

public class MyLinkVisitor extends NodeVisitor {

    public MyLinkVisitor() { }

    public void visitTag(Tag tag) {
        if (tag.getTagName().equals("A")) {
            LinkTag link = (LinkTag) tag;
            link.setLink("http://newLink/"); //implement your logic here
        }
    }
}

Then, create a Parser, parse the HTML string and visit the returned node list:

Parser parser = new Parser(htmlString);
NodeList nl = parser.parse(null);
nl.visitAllNodesWith(new MyLinkVisitor());
System.out.println(nl.toHtml());

This is just one way to do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜