如何删除Xml的节点

本文介绍了如何使用Java的DOM解析器删除XML文档中的特定节点。通过创建DocumentBuilderFactory,设置命名空间感知并验证,然后获取并删除指定节点。关键步骤包括找到要删除的节点,获取其父节点,并调用removeChild方法进行删除。最后,使用Transformer将更新后的文档转换回字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 //删除没有子节点的节点
private String validXML(String strNBCNewAlertNotification) throws Exception{
		    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		     dbFactory.setNamespaceAware(true);
			dbFactory.setValidating(true);
		    DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
		    InputSource is = new InputSource(new StringReader(strNBCNewAlertNotification));
		    Document doc = dbBuilder.parse(is);
		    NodeList domainValueList=doc.getElementsByTagNameNS("*", "actionObject");
		    if(null ==domainValueList || domainValueList.getLength() == 0){
		    	 NodeList domainValueList2=doc.getElementsByTagNameNS("*", "actionObjectList");
		    	 Node node = domainValueList2.item(0);
//这个是重点,自己不能删除自己,找到 父node.getParentNode() 再删除 子.removeChild(node);
		    	 node.getParentNode().removeChild(node);
		    	//save xml
		    	 // XML
		    	 TransformerFactory tf = TransformerFactory.newInstance();
		    	 Transformer t = tf.newTransformer();
		    	 ByteArrayOutputStream bos = new ByteArrayOutputStream();
//拿到删除之后的xml
		    	 t.transform(new DOMSource(doc), new StreamResult(bos));
		    	 strNBCNewAlertNotification = bos.toString();


		    }
		    
		    return strNBCNewAlertNotification;
		    
	   }
	 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值