All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.databasesandlife.util.DomElementReplacer Maven / Gradle / Ivy

There is a newer version: 21.0.1
Show newest version
package com.databasesandlife.util;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

/**
 * Takes a DOM and an element name; 
 * each time that element name is found it is replaced with a specified other element (which may contain other elements).
 *    

* The element name, that is searched for, may exist in any namespace. * The replaced element is changed to be within the namespace of the found element, before insertion * in the destination document. * * @author This source is copyright Adrian Smith and licensed under the LGPL 3. * @see Project on GitHub */ public class DomElementReplacer extends DomParser { public static Element cloneElementAndSetNamespace(Document destDocument, Element source, String newNamespaceUri) { var result = destDocument.createElementNS(newNamespaceUri, source.getNodeName()); var at = source.getAttributes(); for (var a = 0; a < at.getLength(); a++) { var att = (Attr) at.item(a); result.setAttribute(att.getNodeName(), att.getValue()); } for (var child : getSubElements(source, "*")) result.appendChild(cloneElementAndSetNamespace(destDocument, child, newNamespaceUri)); return result; } public static void replace(Element doc, String elementName, Element replace) { for (var e : getSubElements(doc, "*")) { if (e.getNodeName().equals(elementName)) { var r = cloneElementAndSetNamespace(doc.getOwnerDocument(), replace, e.getNamespaceURI()); doc.insertBefore(r, e); doc.removeChild(e); } else replace(e, elementName, replace); } } public static boolean contains(Element doc, String elementName) { for (var e : getSubElements(doc, "*")) if (e.getNodeName().equals(elementName)) return true; else if (contains(e, elementName)) return true; return false; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy