删除标签并使用 Java 更改 XML 中的一行?

remove a tag and alter a line in an XML using Java?

我有一个 XML,我需要使用 Java 从其中删除一整个标签。目前还没有那个标签的具体位置,它可以在任何地方,但它会在 client 标签内。

<xml>

<client id="100" version="2">
    <!--  some stuff here -->

    <derta-config>
        <!--  some stuff here -->
    </derta-config>

    <!--  some stuff here -->

    <!--  some stuff here -->
</client>

我需要从上面的 XML 中完全删除这个 <derta-config> 标签。还有一件事。在同一个 XML 文件中,我只有一次该行的实例 <hello>collect_model = 1</hello>。下面的 world 块可以在任何地方,也可以嵌套在其他各种 world 块中。它也会在 client 标签内,但也可能有其他嵌套。

<world>
    <world>
        <world>
            <world>
                <hello>collect_model = 1</hello>
                <hello>enable_data = 0</hello>
                <hello>session_ms = 1000</hello>
                <hello>max_collect = string_integer($extract("max_collect"))</hello>
                <hello>max_collect = parenting(max_collect, max_collect, 100)</hello>
                <hello>output('{')</hello>
            </world>
        </world>
    </world>
</world>

我需要像这样制作该行:<hello>collect_model = 0</hello> 在同一个 world 块中。所以我的最终 XML 不会有上面的 <derta-config> 标签并且 collect_model 将是 0

<world>
    <world>
        <world>
            <world>
                <hello>collect_model = 0</hello>
                <hello>enable_data = 0</hello>
                <hello>session_ms = 1000</hello>
                <hello>max_collect = string_integer($extract("max_collect"))</hello>
                <hello>max_collect = parenting(max_collect, max_collect, 100)</hello>
                <hello>output('{')</hello>
            </world>
        </world>
    </world>
</world>

下面是我的代码,我不确定我应该怎么做才能删除这些东西?

File fileName = new File("file example");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(fileName);

更新:-

File fileName = new File("file example");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(fileName);

NodeList configTag = document.getElementsByTagName("derta-config");
for (int i = 0; i < configTag.getLength(); i++) {
    Node node = configTag.item(i);
    System.out.println(node.getNodeName());
    node.getParentNode().removeChild(node);
}

接下来你打电话给 document.getElementsByTagName("derta-config"), iterate the list (should be one long, right?), and use node.getParentNode().removeChild(node).

之后,调用document.getElementsByTagName("hello"),遍历列表,使用node.getTextContent(), and if it is the value you want to change, you change it with node.setTextContent(newValue)检查文本内容。

然后将结果保存回文件。参见 How to save parsed and changed DOM document in xml file?