替换 javascript 中 XML 文件的值

replacing value of XML file in javascript

我在我的 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>

我现在尝试首先 select Path1 和 Path2 节点,然后 switch path1 的值与path2 的值。 我 select 如下节点:

 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.

我收到一条错误提示,"An attempt was made to reference a Node in a context where it does not exist"。 知道我哪里做错了吗?

replaceChild 确实意味着替换 child 而不是 great-grandchild.

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

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

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

 firstValue.textContent = secondValue;

 secondValue.textContent = firstValue ;