使用 removeChild() 方法后如何更新 xml 文件

how to update xml file after using removeChild() method

我有 xml 个名为 "movies.xml" 的文件。我需要从中删除第一部电影,所以我创建了 "delete.jsp" 包含所需代码的文件。

这两个文件都存在于 Netbeans 制作的 Java 网络项目文件夹中,我使用 Apache Tomcat 服务器作为本地主机

movies.xml

<?xml version="1.0" encoding="UTF-8"?>
<movies>
    <movie>
        <Title>Journey to the Edge of the Universe</Title>
        <Date>7 December 2008</Date>
        <Publisher>National Geographic</Publisher>
        <Description>
            A journey through space and time.
        </Description>
    </movie>

    <movie>
        <Title>Sea Monsters: A Prehistoric Adventure</Title>
        <Date>5 October 2007</Date>
        <Publisher>National Geographic</Publisher>
        <Description>
            A journey to the bottom of the ancient oceans dramatizes awe-inspiring creatures.
        </Description>
    </movie>
</movies>

delete.jsp

<script>
            function loadXMLDoc() {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        deleteMovie(this);
                    }
                };
                xmlhttp.open("GET", "movies.xml", true);
                xmlhttp.send();
            }

            function deleteMovie(xml) {
                var xmlDoc = xml.responseXML;
                x = xmlDoc.getElementsByTagName("movie")[0];
                x.parentNode.removeChild(x);
            }
</script>

代码工作正常,但是当我打开 xml 文件时,我看不到任何变化。

在 removing/inserting 或没有任何其他语言的任何修改后保存或更新 xml 文件的最佳方法是什么?

删除

移除一个元素节点

假设 "movie.xml" 加载了 xmlDoc 设置变量 x 为要移除的元素节点 使用父节点的removeChild()方法移除元素节点

x = xmlDoc.getElementsByTagName("movie")[0];
 x.documentElement.removeChild(x);

删除我自己 - 删除更改​​文本节点的当前值

x = xmlDoc.getElementsByTagName("movie")[0];

x[0].parentNodechildNodes[0].removeChild(x);nodeValue = "new content"

删除文本节点使用 setAttribute() 更改属性

x = xmlDoc.getElementsByTagName("movie")[0];
y = x.childNodes[0];
x[0].removeChildsetAttribute(y"category","name");

清除文本节点使用节点值更改属性

xmlDoc.getElementsByTagName("movie")[0].childNodes[0]getAttributeNode("category").nodeValue = "";"name";

参考:W3学校

更新:

更改文本节点的值

xmlDoc.getElementsByTagName("movie")[0].childNodes[0].nodeValue = "new content"

使用 setAttribute() 更改属性

xmlDoc.getElementsByTagName("movie")[0].setAttribute("category","name");

使用节点值更改属性

xmlDoc.getElementsByTagName("movie")[0].getAttributeNode("category").nodeValue = "name";

自己试试 »

Remove

Update

Obs.: nodeValue 属性 是属性节点的值。更改值 属性 会更改属性的值。

您的问题是: javaScript 没有 input/output (I/O) API 因为它是客户端端脚本语言,因此无法通过服务器访问文件系统。您需要使用服务器端脚本语言将数据保存到服务器。可能有黑客可以解决您的客户端问题,但它们可能未保存或存在其他问题。 (顺便说一句:api 的 save 方法成员是什么?你编的吗?)

您可以做的是将数据临时保存到任何 DOM 元素(例如 window 或 javaScript)对象。然而,无法使这些更改永久化。

在您的情况下,查看 PHP 或 Node js 脚本可能是最好的方法。 但是这里的代码有效。 参考:here