Here you can find the source of findElementElseCreateAndAttribute(Document document, Element parent, String element, String attributeName, String attributeValue)
public static Element findElementElseCreateAndAttribute(Document document, Element parent, String element, String attributeName, String attributeValue)
//package com.java2s; //License from project: Apache License import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class Main { public static Element findElementElseCreateAndAttribute(Document document, Element parent, String element, String attributeName, String attributeValue) { NodeList nl = parent.getElementsByTagName(element); Element e = null;//ww w . j a va2 s . c om if (nl.getLength() == 0) { parent.appendChild(document.createElement(element)); e = (Element) parent.getElementsByTagName(element).item(0); e.setAttribute(attributeName, attributeValue); } return e; } }