這與另一個問題有關,但是不是的重複。 它涉及我已經陷入僵局的提議解決方案。使用window.open,document.open和document.write來顯示XML(XML呈現不見了)
我有以下代碼讀取XML,進行更改,打開一個窗口,並將XML寫入文檔。問題是內容不是以XML格式呈現的。 設置內容類型等的任何方式讓瀏覽器以XML格式處理內容?
<script>
var wxml;
var xDoc;
var xDevices, xInputs;
var xDevice, xInput;
function fSetXmlAInput(iDevice, iNode, nodeNewVal) {
xInput = xInputs[iNode];
xValue = xInput.getElementsByTagName("value")[0];
// change node value:
// console.log("nodeVal: " + xValue.firstChild.nodeValue);
xValue.firstChild.nodeValue = nodeNewVal;
// console.log("newVal: " + xValue.firstChild.nodeValue);
}
function fSetXmlDevice(iDevice) {
xDevice = xDevices[iDevice];
xInputs = xDevice.getElementsByTagName("input");
fSetXmlAInput(iDevice, 0, "22");
fSetXmlAInput(iDevice, 1, "33");
}
function alternativeLoadXML3() {
// load xml file
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "my_template.xml", false);
xhttp.send();
xDoc = xhttp.responseXML;
xDevices = xDoc.getElementsByTagName("device");
fSetXmlDevice(1);
var xmlText = serializeXmlNode(xDoc);
var newWindow = window.open("my_template.xml", "Test", "width=300,height=300,scrollbars=1,resizable=1");
newWindow.document.open();
newWindow.document.write(xmlText);
newWindow.document.close()
};
</script>
下面的XML以及:
<?xml version="1.0" encoding="utf-8"?>
<myXmlRoot>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
</myXmlRoot>
任何方式強制瀏覽器呈現在新窗口中的XML內容...或使用不document.open和文件撰寫意味着代碼呈現爲HTML?
相關:Change XML content using JavaScript, missing refresh
那麼你會如何使用'sampleElement.appendChild(XMLnode)'在上面的例子中? – 2013-05-09 16:19:36
您需要使用XML解析器加載'my_template.xml',就像您在函數alternativeLoadXML3()中使用的那樣。然後,您可以使用XML DOM將元素附加到文檔。最後,要將XML顯示爲可摺疊的樹,您可以使用JavaScript框架,例如以下網址中提供的JavaScript框架:http://stackoverflow.com/questions/1366179/how-to-display-xml-in-a-html-page -as-a-collapsible-and-expandable-tree-using-jav – KernelPanik 2013-05-09 18:08:23