Android XML Namespace Set registerNamespace(Document d, String targetNamespace)

Here you can find the source of registerNamespace(Document d, String targetNamespace)

Description

register Namespace

License

Open Source License

Declaration

public static void registerNamespace(Document d, String targetNamespace) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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 void registerNamespace(Document d, String targetNamespace) {

        if (targetNamespace == null || targetNamespace.length() == 0)
            return;

        Element e = d.getDocumentElement();
        int i = 0;
        NamedNodeMap map = e.getAttributes();

        String prefix = "ns" + String.valueOf(map.getLength());

        int n = map.getLength();
        for (i = 0; i < n; i++) {
            /*Node node = map.item(i);
            if(node.getNodeType()!=Node.ATTRIBUTE_NODE)
               continue;*///  w w w  .  j a v a 2  s  . com
            Attr attr = (Attr) map.item(i);
            String nsUri = attr.getNamespaceURI();
            if (nsUri == null)
                continue;
            if (nsUri.equals("http://www.w3.org/2000/xmlns/")) {
                if (targetNamespace.equals(attr.getValue()))
                    return;
            }
        }

        Attr atr = d.createAttributeNS("http://www.w3.org/2000/xmlns/",
                "xmlns:" + prefix);
        atr.setValue(targetNamespace);

        e.setAttributeNode(atr);
    }
}