2013年8月2日 星期五

Update a HTML file and convert it back from DOM to String

The target is to that while having a local html file and say you wanna update it with additional code like javascript and load it using WebView.loadDataWithBaseURL(). How are you going to do that ? The idea is to load the local file and transform it to DOM instance, and then you operate on the instance to modify the content, and finally you transform it back to a String instance.

The code snippet:

public String addJSsrc2DOM(String path, String js_url[]) {
        Document doc;
        String result;
       
        /* Convert to Document obj */
        String html_content = assetFile2Str(path);
        MyAndroidJSInterface obj = new MyAndroidJSInterface(mcontext, commonUtility.class);
        doc = obj.parseXML(html_content);
       
        for (int i = -2;;i++) {
            String target_js;
           
            if (i == -2) {
                target_js = "local.js";
            }
            else if (i == -1) {
                target_js = "http://trailers.apple.com/appletv/us/js/application.js";
            }
            else if (js_url[i] == null) {
                break;
            }
            else {
                target_js = js_url[i];
            }
           
            /* Create a script Element to contain JS src info */
            Element script = doc.createElement("script");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("src", target_js);
            doc.getElementsByTagName("head").item(0).appendChild(script);
        }
        result = getStringFromDocument(doc);
        System.out.println(result);
        return result;
    }
   
    private String getStringFromDocument(Document doc)
    {
        try
        {
           DOMSource domSource = new DOMSource(doc);
           StringWriter writer = new StringWriter();
           StreamResult result = new StreamResult(writer);
           TransformerFactory tf = TransformerFactory.newInstance();
           Transformer transformer = tf.newTransformer();
           transformer.transform(domSource, result);
           return writer.toString();
        }
        catch(TransformerException ex)
        {
           ex.printStackTrace();
           return null;
        }
    }
   
    private String assetFile2Str(String path) {
        String str = "";
        try {
            InputStream is = mcontext.getAssets().open(path);
            int size = is.available();

            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();

            str = new String(buffer);
        }
        catch(IOException e) {}
        return str;
    }


Reference links
http://www.theserverside.com/discussions/thread.tss?thread_id=26060

沒有留言:

張貼留言