日期:2014-05-16  浏览次数:20383 次

读取iframe中XML数据问题,跪求高手进
<html>
<head><title></title></head>
<body>
<iframe id="myifr">
<xml version="1.0" encoding="UTF-8" standalone="yes">
<data>
<code>我就要读这个</code>
</data>
</xml>
</iframe>
</body>
</html>
请高手写一下JS获取iframe中xml的code中这段“我就要读这个”


------解决方案--------------------
兄弟这样可以了
HTML code
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
    无标题页
</title></head>
<body>
    <form name="form1" method="post" action="WebForm1.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzgzNDMwNTMzZGSQD9Q3HDt+gXxVAR6MoQPeTvR5mg==" />
</div>
 
    <div>
        <iframe src="XMLFile1.xml" id="myifr">
        </iframe>
    </div>
    <div>       
        <input type="button" value="测试" onclick="fnGetCode();"/>
        <script type="text/javascript">
            function getXMLDom(path) {
                /// <summary>
                /// 加载xmlDom
                /// </summary>
                var xmlDoc = null;
                try {//Internet Explorer  
                    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                } catch (e) {
                    try {//Firefox, Mozilla, Opera, etc.    
                        xmlDoc = document.implementation.createDocument("", "", null);
                    } catch (e) {
                        alert("加载xml文档失败:" + e.message);
                    }
                }
                try {
                    xmlDoc.async = false;
                    var b = xmlDoc.load(path);
                    if (b) {
                        return xmlDoc;
                    }
                } catch (e) {
                    alert("加载xml文档失败:" + e.message);
                    return null;
                }
            }
            function fnGetCode(){                
                var xmlDoc=getXMLDom(document.getElementById("myifr").src);
                alert(xmlDoc.getElementsByTagName("code")[0].text);
            }
        </script>
    </div>
    </form>
</body>
</html>

------解决方案--------------------
这样可以读出来:

JScript code

document.getElementById('myifr').innerHTML.match(/<code>(\w+)<\/code>/g);
alert(RegExp.$1);

------解决方案--------------------
假如document.getElementById('myifr').innerHTML可以获取xml文档的字符串标示的话,用下面这个方法可以转化会xml文档对象。
JScript code

//var xmlDoc = createXmlDoc(document.getElementById('myifr').innerHTML);
//xmlDoc.getElementsByTagName("code")[0]
function createXmlDoc(xmlText) {
    if (!xmlText) return null;
    try {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM")
        xmlDom.loadXML(xmlText)
        return xmlDom
    }
    catch (e) {
        try {
            return new DOMParser().parseFromString(xmlText, "text/xml");
        } catch (e) {
            return null;
        }
    }
}