create Node for Document - Java XML

Java examples for XML:XML Node

Description

create Node for Document

Demo Code


//package com.java2s;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

public class Main {
    public static Element createNode(Document d, String nameSpace,
            String name) {//w  w  w .j av a2  s  .c  o m
        if (nameSpace == null || nameSpace.length() == 0)
            return d.createElement(name);
        Element e = d.createElementNS(nameSpace, name);

        // get prefix...
        NamedNodeMap map = d.getDocumentElement().getAttributes();
        int i = 0;
        int n = map.getLength();
        for (i = 0; i < n; i++) {
            Attr attr = (Attr) map.item(i);
            String nsUri = attr.getNamespaceURI();
            if (nsUri == null)
                continue;
            if (nsUri.equals("http://www.w3.org/2000/xmlns/")
                    && attr.getValue().equals(nameSpace)) {
                // found prefix...
                e.setPrefix(attr.getLocalName());
            }
        }

        return e;
    }
}

Related Tutorials