Here you can find the source of deleteXMLElement(String xml, String xpath)
public static String deleteXMLElement(String xml, String xpath)
//package com.java2s; /**/*from ww w .ja v a2 s . c o m*/ * Copyright (c) Microsoft Corporation * * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.StringReader; import java.io.StringWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; public class Main { public static String deleteXMLElement(String xml, String xpath) { try { final Node node = findXMLNode(xml, xpath); Node parent = node.getParentNode(); parent.removeChild(node); return XMLtoString(parent.getOwnerDocument()); } catch (XPathExpressionException e) { return null; } } static public Node findXMLNode(String xml, String xpath) throws XPathExpressionException { final InputSource parentSource = new InputSource(new StringReader(xml)); final XPath xpathObject = XPathFactory.newInstance().newXPath(); return (Node) xpathObject.evaluate(xpath, parentSource, XPathConstants.NODE); } static String XMLtoString(Document doc) { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.getBuffer().toString(); } catch (Exception e) { return null; } } }