Java getElementById()或Alternative

时间:2013-11-01 14:01:03

标签: java xhtml getelementbyid

所以,我有一个XHTML文档报告框架,我希望通过获取某些ID的元素并设置其内容来填充。

我尝试了getElementById(),并返回null(因为,我发现,id不是隐式“id”,需要在模式中声明)。

panel.setDocument(Main.class.getResource("/halreportview/DefaultSiteDetails.html").toString());
panel = populateDefaultReport(panel);

Element header1 = panel.getDocument().getElementById("header1");
header1.setTextContent("<span class=\"b\">Instruction Type:</span> Example<br/><span class=\"b\">Allocated To:</span> "+employee.toString()+"<br/><span class=\"b\">Scheduled Date:</span> "+dateFormat.format(scheduledDate));

所以,我尝试了一些解决方法,因为我不想验证我的XHTML文档。我尝试将快速DTD添加到相关文件的顶部,如此;

<?xml version="1.0"?>
<!DOCTYPE foo [<!ATTLIST bar id ID #IMPLIED>]>

但是getElementById()仍然返回null。所以尝试在XHTML文档中使用xml:id代替id,希望它得到支持,但再次没有运气。所以我尝试使用getElementsByTagName()并遍历结果检查ID。这工作,并找到正确的元素(由输出打印“发现它”确认),但当我尝试在此元素上调用setTextContent时,我仍然得到一个NullPointException。代码如下;

    Element header1;
    NodeList sections = panel.getDocument().getElementsByTagName("p");
    for (int i = 0; i < sections.getLength(); ++i) {
         if (((Element)sections.item(i)).getAttribute("id").equals("header1")) {
            System.out.println("Found it");
            header1 = (Element) sections.item(i);
            header1.setTextContent("<span class=\"b\">Instruction Type:</span> Example<br/><span class=\"b\">Allocated To:</span> "+employee.toString()+"<br/><span class=\"b\">Scheduled Date:</span> "+dateFormat.format(scheduledDate));
        }
    }

我对这个问题感到失望。我必须遭受某种根本的误解,认为这应该如何发挥作用。有什么想法吗?

编辑;下面摘录了我的XHTML文件,删除了CSS。

<html>
<head>
    <title>Site Details</title>
    <style type="text/css">
    </style>
</head>
<body>
    <div class="header">
        <p></p>
        <img src="#" alt="Logo" height="81" width="69"/>
        <p id="header1"><span class="b">Instruction Type:</span> Example<br/><span class="b">Allocated To:</span> Example<br/><span class="b">Scheduled Date:</span> Example</p> 
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我不确定为什么它不起作用,但我已经为你做了一个例子,它有效!

注意:我的示例使用以下库

  1. Apache Commons IO(Link
  2. Jsoup HTML Parser(Jsoup link)
  3. Apache Commons Lang(Link
  4. 我的输入xhtml文件,

    <html>
    <head>
    <title>Site Details</title>
    <style type="text/css">
    </style>
    </head>
    <body>
        <div class="header">
            <p></p>
            <img src="#" alt="Logo" height="81" width="69" />
            <p id="header1">
                <span class="b">Instruction Type:</span> Example<br />
                <span class="b">Allocated To:</span> Example<br />
                <span class="b">Scheduled Date:</span> Example
            </p>
        </div>
    </body>
    </html>
    

    有效的java代码! [所有评论,阅读]

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Date;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.io.IOUtils;
    import org.apache.commons.lang3.StringEscapeUtils;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    public class Test {
    
        /**
         * @param args
         * @throws IOException
         * @throws InterruptedException
         */
        public static void main(String[] args) throws IOException, InterruptedException {
            //loading file from project
            //When it is exported as JAR the files inside jar are not files but they are stream
            InputStream stream = Test.class.getResourceAsStream("/test.xhtml");
    
            //convert stream to file
            File xhtmlfile = File.createTempFile("xhtmlFile", ".tmp");
            FileOutputStream fileOutputStream = new FileOutputStream(xhtmlfile);
            IOUtils.copy(stream, fileOutputStream);
            xhtmlfile.deleteOnExit();
    
            //get html string from file
            String htmlString = FileUtils.readFileToString(xhtmlfile);
    
            //parse using jsoup
            Document doc = Jsoup.parse(htmlString);
    
            //get all elements
            Elements allElements = doc.getAllElements();
    
    
            for (Element el : allElements) {
                //if element id is header 1
                if (el.id().equals("header1")) {
    
                    //dummy emp name
                    String employeeName = "dummyEmployee";
                    //update text
                    el.text("<span class=\"b\">Instruction Type:</span> Example<br/><span class=\"b\">Allocated To:</span> "
                            + employeeName.toString() + "<br/><span class=\"b\">Scheduled Date:</span> " + new Date());
                    //dont loop further
                    break;
                }
            }
    
            //now get html from the updated document
            String html = doc.html();
    
            //we need to unscape html 
            String escapeHtml4 = StringEscapeUtils.unescapeHtml4(html);
    
            //print html 
            System.out.println(escapeHtml4);
    
        }
    
    }
    

    * 输出*

    <html>
     <head> 
      <title>Site Details</title> 
      <style type="text/css">
    </style> 
     </head> 
     <body> 
      <div class="header"> 
       <p></p> 
       <img src="#" alt="Logo" height="81" width="69" /> 
       <p id="header1"><span class="b">Instruction Type:</span> Example<br/><span class="b">Allocated To:</span> dummyEmployee<br/><span class="b">Scheduled Date:</span> Sat Nov 02 07:37:12 GMT 2013</p> 
      </div>  
     </body>
    </html>