由于活动的X解析器,我下面有一段代码仅可用于IE,我需要在chrome和其他最新的浏览器中运行它。
< script language = "jscript" type = "text/javascript" >
function Transform1() {
var xml1 = new ActiveXObject("Microsoft.XMLDOM");
xml1.async = false; xml1.load(frmSoap.TestXml.value);
frmSoap.Body.value = xml1.xml;
}
< /script>
我尝试通过使用以下更改来修复它,但它对我不起作用,而是也停止在ie中工作。
function Transform1()
if (window.DOMParser) {
var parser, xml1;
parser = new DOMParser();
xml1 = parser.parseFromString(frmSoap.TestXml.value,"text/xml");
frmSoap.Body.value = xml1.xml;
} else {
var xml1 = new ActiveXObject("Microsoft.>XMLDOM");
xml1.async = false;
xml1.load(frmSoap.TestXml.value);
frmSoap.Body.value = xml1.xml;
}
有人可以帮我解决这个问题。
答案 0 :(得分:0)
这是一种适用于所有浏览器的方法。通过使用createDocument()
,然后让浏览器为您解析XML。
请参阅代码中的注释。
//Mock
const frmSoap = {
TestXml: {
value: `<productListing title="ABC Products">
<product>
<name>Product One</name>
<description>Product One is an exciting new widget that will
simplify your life.</description>
<cost>$19.95</cost>
<shipping>$2.95</shipping>
</product>
</productListing>`
}
}
// Create an XHTML document
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'xhtml', null);
// Add body
var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body');
doc.documentElement.appendChild(body);
// Parse the XML document and place it in the new XML doc body
body.innerHTML = frmSoap.TestXml.value;
//Parse the XML to produce output
const title = body.querySelector('productListing').getAttribute('title');
const productName = body.querySelector("product name").textContent;
const productDescription = body.querySelector("product description").textContent;
//Use the XML data
document.getElementById("output").innerHTML = `<h1>${title}</h1><span>Product Name:</span> ${productName}, <br><span>Product Description:</span> ${productDescription}`;
// Remove the doc when no longer needed
doc = null;
span {
font-weight: bold;
}
<div id="output"></div>