Java XML Element Create findElementElseCreateAndSetAndAttribute(Document document, Element parent, String element, String value, String attributeName, String attributeValue)

Here you can find the source of findElementElseCreateAndSetAndAttribute(Document document, Element parent, String element, String value, String attributeName, String attributeValue)

Description

find Element Else Create And Set And Attribute

License

Apache License

Declaration

public static Element findElementElseCreateAndSetAndAttribute(Document document, Element parent, String element,
            String value, String attributeName, String attributeValue) 

Method Source Code

//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 findElementElseCreateAndSetAndAttribute(Document document, Element parent, String element,
            String value, String attributeName, String attributeValue) {

        Element e = findElementElseCreateAndAttribute(document, parent, element, attributeName, attributeValue);
        if (e != null)
            e.appendChild(document.createTextNode(value));

        return e;
    }//from ww w  . j  av a 2s  .c  o m

    public static Element findElementElseCreateAndAttribute(Document document, Element parent, String element,
            String attributeName, String attributeValue) {
        NodeList nl = parent.getElementsByTagName(element);
        Element e = null;

        if (nl.getLength() == 0) {
            parent.appendChild(document.createElement(element));
            e = (Element) parent.getElementsByTagName(element).item(0);
            e.setAttribute(attributeName, attributeValue);
        }

        return e;
    }
}

Related

  1. createText(Node parent, String tag, String text)
  2. createText(String sValue, Node nParent)
  3. createTextElement(Element parent, String tagName, String text)
  4. createTextElement2(Element parent, String tagName, String text)
  5. findElementElseCreateAndAttribute(Document document, Element parent, String element, String attributeName, String attributeValue)