用javascript替换XML文件的值

replacing value of XML file in javascript

本文关键字:文件 XML javascript 替换      更新时间:2023-09-26

我在js文件中使用XMLHTTPRequest加载一个XML文档。XML文件如下所示:

  <?xml version="1.0" encoding="utf-8"?>
  <RMFSFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Host>www.example.com</Host>
  <Port>8888</Port>   
  <Uri>www.example.com</Uri>
<Path>
     <HD>
        <UNC>path1</UNC>
    </HD>
    <SD>
       <UNC>path2</UNC>
    </SD>
</Path>

我现在尝试首先选择Path1和Path2节点,然后Path1的值切换为Path2。我选择如下节点:

 var firstNode = xmlFile.querySelector('Path>HD>UNC'); '' I can get the node successfully. 
 var secondNode= xml.querySelector('Path>SD>UNC');  '' I can get the node successfully. 

但是,当我尝试使用以下代码替换值时:

    xmlFile.replaceChild(secondNode,firstNode) // secondNode, is the new value for first node.

我收到一个错误,上面写着:"试图在不存在节点的上下文中引用节点"。你知道我哪里做错了吗?

replaceChild确实意味着替换孩子而不是曾孙。

您需要将xmlFile替换为要替换的元素的父节点。

与其交换节点,不如交换它们的内容,如下所示:

 var firstValue =xmlFile.querySelector('Path>HD>UNC').textContent;                                    
 var secondValue= xmlFile.querySelector('Path>HD>UNC').textContent;
 firstValue.textContent = secondValue;
 secondValue.textContent = firstValue ;