使用窗口.开放、文档.打开,并记录.写入显示XML (XML呈现消失)

Using window.open, document.open, and document.write to display XML (XML rendering gone)

本文关键字:XML 显示 消失 记录 开放 窗口 文档 打开      更新时间:2023-09-26

这与另一个问题有关,但是不是是重复的吗?它是关于一个我已经陷入僵局的提议的解决方案。

我有以下代码,读取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格式呈现内容的方法…或者使用文档。打开并归档。编写平均代码呈现为HTML?

相关:使用JavaScript更改XML内容,缺少刷新

使用dataURI将xml写入新窗口非常简单。

window.open('data:text/xml,'+encodeURIComponent(xmlText),
     "Test", "width=300,height=300,scrollbars=1,resizable=1");

两个文档。open和document.write用于将HTML或Javascript写入文档。这可以追溯到文档的DOM第2级规范。open,它假定打开文档是为了编写未解析的HTML。

不使用document.opendocument.write,我建议使用XML DOM动态添加元素,如sampleElement.appendChild(XMLnode)

一个类似的问题也可以在这里找到:如何在javascript中显示xml ?