如何在IE 8中将HTML DOM序列化为XML?

时间:2011-07-18 09:30:17

标签: html dom

有没有办法在IE 8或任何其他旧版IE中执行此操作(将HTML DOM序列化为XML)。
在firefox中:

var xmlString = new XMLSerializer().serializeToString( doc );

做到了。
虽然我没有尝试过。

XMLSerializer在IE 8中导致错误,它未定义。

1 个答案:

答案 0 :(得分:0)

var objSerializeDOM = {

//Variable to hold generated XML.   
msg : "",   

serializeDOM : function() {

    dv = document.createElement('div'); // create dynamically div tag
    dv.setAttribute('id', "lyr1"); // give id to it
    dv.className = "top"; // set the style classname
    // set the inner styling of the div tag
    dv.style.position = "absolute";

    // set the html content inside the div tag
    dv.innerHTML = "<input type='button' value='Serialize' onClick='objSerializeDOM.createXML()'/>"
    "<br>";

    // finally add the div id to ur form
    document.body.insertBefore(dv, document.body.firstChild);

},

/**
 * XML creation takes place here.
 */
createXML : function() {

    objSerializeDOM.msg += "";
    objSerializeDOM.msg += "<?xml version='1.0' encoding='UTF-8'?>\n\n";
    // Get all the forms in a document.
    var forms = document.forms;

    for ( var i = 0; i < forms.length; i++) {
        // Get all the elements on per form basis.
        elements = document.forms[i].elements;
        objSerializeDOM.msg += "<FORM name=\"" + forms[i].name + "\" method=\""
                + forms[i].method + "\" action=\"" + forms[i].action + "\">\n\n";
        for ( var j = 0; j < elements.length; j++) {
            objSerializeDOM.msg += "    <" + elements[j].tagName + "  type=\""
                    + elements[j].type + "\"" + "  name=\""
                    + elements[j].name + "\"" + "   Value =\""
                    + elements[j].value + "\"  />\n";
        }
        alert(document.forms[i].elements[1].event);
    }
    objSerializeDOM.msg += "\n\n</FORM>\n\n";
    alert(objSerializeDOM.msg);
    objSerializeDOM.writeToFile(objSerializeDOM.msg);
},

/**
 * Writes the msg to file at pre-specified location.
 * @param msg
 *          the XML file created.
 */
writeToFile : function(msg) {
   var fso  = new ActiveXObject("Scripting.FileSystemObject");
   var fh = fso.CreateTextFile("c:\\myXML.xml", true);
   fh.WriteLine(msg);
   fh.Close();
}

};

objSerializeDOM.serializeDOM();

我写了这个JS,我使用GreaseMonkey4IE运行这个javascript。这只是在GM4IE中指定的域的每个页面上放置一个按钮。单击该按钮,它将解析HTML文档并创建XML文件。它还将首先显示相同的警报,并将XML保存在指定路径上的本地驱动器中 我还打算做很多改进,但是它确实有效,可能会给你们一个想法。
我希望这个程序不言自明。
请看这里How to get Events associated with DOM elements?

谢谢