java xpath 从xml中删除元素 [英] java xpath remove element from xml

查看:25
本文介绍了java xpath 从xml中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 xml 文件中删除一个元素和子元素.特别是名称为 Testlogging 的 appender.

I am trying to remove an element and child elements from an xml file. Specifically appender with the name Testlogging.

首先这是我的 xml 文件的外观.

First this is how my xml file looks.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="null" threshold="null">

<appender class="DailyLogFileAppender" name="Testlogging">
    <param name="encoding" value="UTF-8"/>
    <param name="MaxFileSize" value="100MB"/>
    <param name="MaxBackupIndex" value="2"/>
    <param name="rootDir" value="c:\Logs"/>
    <param name="componentId" value="Testlogging"/>
    <param name="DatePattern" value="yyyyMMdd"/>
    <layout class="SyslogPatternLayout">
        <param ConversionPattern="%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} [%-5p] {%t} %c [%D] - %m%n"/>
    </layout>
</appender>

这是我的java代码:

Here is my java code:

DocumentBuilderFactory dbfact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbfact.newDocumentBuilder();
Document d = builder.parse(xmlFile);
        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList nl = (NodeList)xp.compile("//appender").evaluate(d,XPathConstants.NODESET);

        for(int i = 0; i < nl.getLength(); i++)
        {
            if(xp.compile("./@name").evaluate(nl.item(i)).equals("Testlogging"))
            {
                Node node = nl.item(i);
                node.removeChild(nl.item(i));
            }
        }

我想删除此 appender 的所有内容,但正在引发异常.这可能是我遗漏的一些简单的东西.

I would like to remove everything for this appender but an exception is being thrown. It's probably something simple I am missing.

有什么想法吗?

推荐答案

那么你需要在你要移除的节点的父节点上调用 removeChild 并且你需要处理NodeList 以相反的顺序(因为 W3C DOM 集合是实时"集合,可以随着任何 DOM 操作而改变(https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#td-live)) 所以使用像

Well you need to call removeChild on the parent node of the node you want to remove and you need to process the NodeList in reverse order (as W3C DOM collections are "live" collections that can change with any DOM manipulation (https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#td-live)) so use an approach like

    NodeList nl = (NodeList)xp.compile("//appender[@name = 'Testlogging']").evaluate(d,XPathConstants.NODESET);
    for (int i = nl.getLength() - 1; i >= 0; i--) 
    {
       nl.item(i).getParentNode().removeChild(nl.item(i));
    }

这篇关于java xpath 从xml中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆