有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个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);
}

共 (1) 个答案

  1. # 1 楼答案

    接下来调用^{},迭代列表(应该是一个长列表,对吗?),并使用^{}

    之后,调用document.getElementsByTagName("hello"),迭代列表,使用^{}检查文本内容,如果它是您想要更改的值,则使用^{}更改它

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