【问题标题】:replacing value of XML file in javascript在javascript中替换XML文件的值
【发布时间】:2016-03-10 08:03:11
【问题描述】:

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

我收到一条错误消息,“试图在不存在的上下文中引用节点”。 有什么想法我做错了吗?

【问题讨论】:

    标签: javascript xml xml-parsing xmlhttprequest


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-01-28
        • 1970-01-01
        • 1970-01-01
        • 2017-08-07
        • 2021-11-06
        • 1970-01-01
        • 2016-11-26
        • 1970-01-01
        • 2020-01-17
        相关资源
        最近更新 更多