使用 JavaScript/AJAX 连接两个 XML 文件

Concatenating two XML files using JavaScript/AJAX

本文关键字:两个 XML 文件 JavaScript AJAX 连接 使用      更新时间:2023-09-26

>我的任务是将XML文件分成两部分,以便于编辑。

但是所有现有的代码库都旨在将其视为单个文件。

作为中间立场(由于时间不足(,我决定拆分文件,但只需使用以下代码连接拆分文件

    var xmlDoc;
    xmlhttp.open("GET","distributome-relations.xml",false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;
    xmlhttp=createAjaxRequest();
    xmlhttp.open("GET","distributome-references.xml",false);
    xmlhttp.send();
    xmlDoc = xmlDoc+xmlhttp.responseXML;
            try{
        DistributomeXML_Objects=xmlDoc.documentElement.childNodes;
    }catch(error){
        DistributomeXML_Objects=xmlDoc.childNodes;
    }

这似乎不起作用,而原始代码

xmlhttp.open("GET","Distributome.xml",false);
    xmlhttp.send();
    if (!xmlhttp.responseXML.documentElement && xmlhttp.responseStream)
        xmlhttp.responseXML.load(xmlhttp.responseStream);
    xmlDoc = xmlhttp.responseXML;
    try{
        DistributomeXML_Objects=xmlDoc.documentElement.childNodes;
    }catch(error){
        DistributomeXML_Objects=xmlDoc.childNodes;
    }

工作得很好。

我不确定如何继续这样做。

我只是简单地拆分了文件

http://www.distributome.avinashc.com/avinash/Distributome.xml 成

http://www.distributome.avinashc.com/avinash/distributome-relations.xml 和http://www.distributome.avinashc.com/avinash/distributome-references.xml

最后两个文件的

格式不正确,因为只有两个文件的简单串联才应该是有效的 XML 文档。

我怀疑这是由于使用了 responseXML 方法,我应该使用另一种方法。

有没有更好的方法可以做到这一点。我欢迎任何建议,当然 - 回答我最初的问题。

谢谢

如果您解释doesn't seem to work转换为什么会有所帮助,但通过快速浏览您的代码,我可以看出您正在尝试使用 + 连接两个DOM Document对象。这一行:

xmlDoc = xmlDoc + xmlhttp.responseXML;

XHR 的 responseXML 属性不会像您期望的那样返回字符串(顺便说一句,像这样连接两个 XML 文件可能会导致格式不正确的 XML(。第二个示例正确地处理了它 - DOM 文档对象。

您可以在MDN上阅读有关responseXML的更多信息。请注意有关Content-Type的说明,以及您可能需要如何使用 XHR 上的overrideMimeType(),以使它相信如果服务器未正确设置标头,它从服务器接收了 XML。

要以XML感知的方式进行连接,您需要从第二个文档(document.documentElement(中获取根节点,使用importNode()将其导入到第一个文档中,然后将其作为子节点附加到您希望使用它的位置appendChild()