java xml 删除节点,使用java解析器删除XML节点

该博客介绍了如何利用Java的XPath能力,针对XML文档找到E值为13的'B'节点,并从其父节点中删除。通过提供的一种替代DOM方法,实现了对XML结构的高效修改,避免了暴力遍历。这种方法在结构变化时易于维护,且随着文档深度增加,代码复杂度保持不变。
摘要由CSDN通过智能技术生成

In the below sample XML, how to remove Entire B Node if E=13 using java parser.

11

12

13

14

Please advise.

解决方案

Alternative DOM Approach

Alternatively, instead of doing a brute force traversal of the XML document you could use the XPath capabilities in the JDK to find the "B" element with value "13" and then remove it from its parent:

import java.io.File;

import javax.xml.parsers.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import javax.xml.xpath.*;

import org.w3c.dom.*;

public class Demo {

public static void main(String[] args) throws Exception {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

Document document = dbf.newDocumentBuilder().parse(new File("input.xml"));

XPathFactory xpf = XPathFactory.newInstance();

XPath xpath = xpf.newXPath();

XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]");

Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);

b13Node.getParentNode().removeChild(b13Node);

TransformerFactory tf = TransformerFactory.newInstance();

Transformer t = tf.newTransformer();

t.transform(new DOMSource(document), new StreamResult(System.out));

}

}

The advantage of using an XPath it's easier to maintain, if the structure changes it's just a one line change to your code. Also if the depth of your document grows the XPath based solution stays the same number of lines.

Non-DOM Approach

If you don't want to materialize your XML as a DOM. You could use a Transformer and a stylesheet to remove a node:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值