'How to append HTML text to div tag in Java

I am dynamically generating a HTML file in Java Selenium Webdriver. The HTML file has two div tags with each having their own unique id attribute.

I want to dynamically add HTML text to these div tags based upon their id's at a later point in my code.

Can this be achieved? If yes, can someone point me in right direction in regards to how to achieve this? If no, what is an alternative way to achieve this?

I am struggling to tackle this scenario. I really need to be able to dynamically append the data to the HTML page based on div tags.

Thanks in advance!

public void createsummaryfile(String report,String path) throws IOException{            
    File summary;       
    summary = new File(filepath);
    if(!summary.exists()){
        summary.createNewFile();
    }
    BufferedWriter bw = new BufferedWriter(new FileWriter(summary));
    bw.write("<!DOCTYPE html>");
    bw.write("<html><head><h1 align=center>EDC Reports Test Case Execution Summary</h1>");
    bw.write("<style>#report_table{height: 300px;left: 1em;position: relative;top: 5em;width: 300px;}#report{height: 300px;left: 20em;position: relative;top: -15em;width: 300px;}</style></head>");
    bw.write("<body><div id=report_table><table align=center border=1><tbody><tr><th>Report Name</th></tr></div>");
    bw.write("<body><div id=report_display></div>");
    bw.write("</html>");        
    bw.close();
}

public void populate_summary(String report,String path) throws IOException{     
    File summary_report = new File(filepath);
    BufferedWriter br = new BufferedWriter(new FileWriter(summary_report,true));        
    //Here I need to access the div tags by their id's and start appending data     
}


Solution 1:[1]

Finding a div-tag with a specific ID inside your HTML document is possible by creating and searching through the DOM tree.

First you need to create a DOM representation of your document:

public static String addToDivWithID(String htmlDocPath, String divID, String dataToAppend)
        throws ParserConfigurationException, IOException, SAXException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(htmlDocPath);

    Element elementWithID = findDiv(divID, doc.getDocumentElement());

    Element contentToAppend = builder
            .parse(new ByteArrayInputStream(dataToAppend.getBytes()))
            .getDocumentElement();

    elementWithID.appendChild(contentToAppend);

    return domToString(doc);
}

In this example I use this method to find the required div-element: It is performing a recursive lookup (the implementation could look a bit better)

public static Element findDiv(String id, Element element) {

    if( id.equals(element.getAttribute("id")) ) {
        return element;
    }

    NodeList innerDivs = element.getElementsByTagName("div");

    for(int i = 0; i < innerDivs.getLength(); i++) {
        Element current = (Element) innerDivs.item(i);

        if( id.equals(current.getAttribute("id")) ) {
            return current;
        }

        Element possibleChildWithID = findDiv(id, current);

        if(possibleChildWithID != null) {
            return possibleChildWithID;
        }
    }

    return null;
}

After finding the correct element, you can add the new content with these lines (already in the first method):

Element contentToAppend = builder
            .parse(new ByteArrayInputStream(dataToAppend.getBytes()))
            .getDocumentElement();

You can find more about appending XML-strings to a DOM-element here.

Then, you have to transform your DOM-document back to its string representation this way:

public static String domToString(Document doc) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

    return output;
}

More info about transforming DOM-documents to string here.

At last it is a personal concern of mine to mention, that you should not handle your HTML-documents this way! If you want to add content in specific divs, use JSP on the server side like this:

<html>
    <body>
        <div id="first">
            <%
                String first = Foo.getFirstDivStuff();
            %>
            <%= first %>
        </div>
        <div id="second">
            <%
                String second = Foo.getSecondDivStuff();
            %>
            <%= second %>
        </div>
    </body>
</html>

If you want to modify HTML-content which already did its way to the client, use AJAX and a proper JSP or Servlet on the server.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community