简体   繁体   English

如何在 Java 中将 HTML 文本附加到 div 标签

[英]How to append HTML text to div tag in Java

I am dynamically generating a HTML file in Java Selenium Webdriver.我在 Java Selenium Webdriver 中动态生成一个 HTML 文件。 The HTML file has two div tags with each having their own unique id attribute. HTML 文件有两个 div 标签,每个标签都有自己唯一的 id 属性。

I want to dynamically add HTML text to these div tags based upon their id's at a later point in my code.我想在稍后的代码中根据它们的 id 向这些 div 标签动态添加 HTML 文本。

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.我真的需要能够根据 div 标签动态地将数据附加到 HTML 页面。

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     
}

Finding a div -tag with a specific ID inside your HTML document is possible by creating and searching through the DOM tree.通过创建和搜索 DOM 树,可以在 HTML 文档中查找具有特定 ID 的div标签。

First you need to create a DOM representation of your document:首先,您需要创建文档的 DOM 表示:

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)在这个例子中,我使用这个方法来查找所需的div元素:它正在执行递归查找(实现可能看起来更好一些)

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 .您可以在此处找到有关将 XML 字符串附加到 DOM 元素的更多信息

Then, you have to transform your DOM-document back to its string representation this way:然后,您必须以这种方式将 DOM 文档转换回其字符串表示形式:

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 .有关将 DOM 文档转换为字符串的更多信息,请点击此处

At last it is a personal concern of mine to mention, that you should not handle your HTML-documents this way!最后要提一下我个人的一个问题,你不应该以这种方式处理你的 HTML 文档! If you want to add content in specific divs, use JSP on the server side like this:如果要在特定的 div 中添加内容,请在服务器端使用 JSP,如下所示:

<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.如果您想修改已经到达客户端的 HTML 内容,请在服务器上使用 AJAX 和适当的 JSP 或 Servlet。

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

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