0

I have read the content of HTML into string, now I need to add a new attribute inside the body tag, I was thinking of using StringBuilder for this. But I am unable to frame the logic. Any help would be really appreciated.

Existing HTML

<body class="temporaryrevision">

HTML that I want to create

<body class="temporaryrevision" bgcolor="#FFFFFF">

4
  • 2
    Use an appropriate object model, make your life easier, something like jsoup for example... Commented May 23, 2014 at 6:09
  • Do you have to do this in Java ? do you have to actually set the bgcolor on the HTML tag (no use of a CSS file) ? Can you provide a little bit more context to your problem to help us answer it ? Commented May 23, 2014 at 6:12
  • Yes I am currently trying to do this in java, I want to append a new attribute in HTML body tag, I don't want it in CSS. Commented May 23, 2014 at 6:15
  • what about using jquery? Commented May 23, 2014 at 6:26

3 Answers 3

2
String htmlString="<html>...<body class="temporaryrevision">..</body>...</html>";  
String[] tempData=htmlString.split("<body class=/"temporaryrevision/""); 
String data = tempData[0]+"bgcolor=/"#FFFFFF/""+tempData[1];
Sign up to request clarification or add additional context in comments.

Comments

1

You can use jQUery for this:

$( ".temporaryrevision" ).attr( "bgcolor", "#FFFFFF" );

Comments

0

Ill suggets a way that will be generic:

Use a XML parser for the same.

  1. Load the file into java and pass it to and instance of XML Parser(SAXParser or something like that)
  2. Traverse the parsed Object tree to your required element tag name. in this example HTML
  3. use Library method to add attribute to the element.
  4. convert the object back to xml format(Basic HTML).
  5. Write and replace the file contents with your updated content.

This way is complex but will be generic to all ur such needs..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.