Example usage for org.w3c.dom Attr getNamespaceURI

List of usage examples for org.w3c.dom Attr getNamespaceURI

Introduction

In this page you can find the example usage for org.w3c.dom Attr getNamespaceURI.

Prototype

public String getNamespaceURI();

Source Link

Document

The namespace URI of this node, or null if it is unspecified (see ).

Usage

From source file:org.chiba.xml.xforms.constraints.Validator.java

private static boolean isInstanceAttribute(Attr attr) {
    if (attr.getNamespaceURI() == null) {
        return true;
    }//from w  ww  . j a v a2  s  .co m

    if (NamespaceCtx.XML_NS.equals(attr.getNamespaceURI())) {
        return false;
    }

    if (NamespaceCtx.XMLNS_NS.equals(attr.getNamespaceURI())) {
        return false;
    }

    if (NamespaceCtx.XMLSCHEMA_INSTANCE_NS.equals(attr.getNamespaceURI())) {
        return false;
    }

    return true;
}

From source file:org.dita.dost.util.XMLUtils.java

/**
 * Add or set attribute. Convenience method for {@link #addOrSetAttribute(AttributesImpl, String, String, String, String, String)}.
 * /* w  w  w .ja v  a2 s .  co m*/
 * @param atts attributes
 * @param att attribute node
 */
public static void addOrSetAttribute(final AttributesImpl atts, final Node att) {
    if (att.getNodeType() != Node.ATTRIBUTE_NODE) {
        throw new IllegalArgumentException();
    }
    final Attr a = (Attr) att;
    String localName = a.getLocalName();
    if (localName == null) {
        localName = a.getName();
        final int i = localName.indexOf(':');
        if (i != -1) {
            localName = localName.substring(i + 1);
        }
    }
    addOrSetAttribute(atts, a.getNamespaceURI() != null ? a.getNamespaceURI() : NULL_NS_URI, localName,
            a.getName() != null ? a.getName() : localName, a.isId() ? "ID" : "CDATA", a.getValue());
}

From source file:org.docx4j.XmlUtils.java

/**
 * Copy a node from one DOM document to another.  Used
 * to avoid relying on an underlying implementation which might 
 * not support importNode /*from  w w w.  j  a  v  a 2  s.c o  m*/
 * (eg Xalan's org.apache.xml.dtm.ref.DTMNodeProxy).
 * 
 * WARNING: doesn't fully support namespaces!
 * 
 * @param sourceNode
 * @param destParent
 */
public static void treeCopy(Node sourceNode, Node destParent) {

    // http://osdir.com/ml/text.xml.xerces-j.devel/2004-04/msg00066.html
    // suggests the problem has been fixed?

    // source node maybe org.apache.xml.dtm.ref.DTMNodeProxy
    // (if its xslt output we are copying)
    // or com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl
    // (if its marshalled JAXB)

    log.debug("node type" + sourceNode.getNodeType());

    switch (sourceNode.getNodeType()) {

    case Node.DOCUMENT_NODE: // type 9
    case Node.DOCUMENT_FRAGMENT_NODE: // type 11

        //              log.debug("DOCUMENT:" + w3CDomNodeToString(sourceNode) );
        //              if (sourceNode.getChildNodes().getLength()==0) {
        //                 log.debug("..no children!");
        //              }

        // recurse on each child
        NodeList nodes = sourceNode.getChildNodes();
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                log.debug("child " + i + "of DOCUMENT_NODE");
                //treeCopy((DTMNodeProxy)nodes.item(i), destParent);
                treeCopy((Node) nodes.item(i), destParent);
            }
        }
        break;
    case Node.ELEMENT_NODE:

        // Copy of the node itself
        log.debug("copying: " + sourceNode.getNodeName());
        Node newChild;
        if (destParent instanceof Document) {
            newChild = ((Document) destParent).createElementNS(sourceNode.getNamespaceURI(),
                    sourceNode.getLocalName());
        } else if (sourceNode.getNamespaceURI() != null) {
            newChild = destParent.getOwnerDocument().createElementNS(sourceNode.getNamespaceURI(),
                    sourceNode.getLocalName());
        } else {
            newChild = destParent.getOwnerDocument().createElement(sourceNode.getNodeName());
        }
        destParent.appendChild(newChild);

        // .. its attributes
        NamedNodeMap atts = sourceNode.getAttributes();
        for (int i = 0; i < atts.getLength(); i++) {

            Attr attr = (Attr) atts.item(i);

            //                  log.debug("attr.getNodeName(): " + attr.getNodeName());
            //                  log.debug("attr.getNamespaceURI(): " + attr.getNamespaceURI());
            //                  log.debug("attr.getLocalName(): " + attr.getLocalName());
            //                  log.debug("attr.getPrefix(): " + attr.getPrefix());

            if (attr.getNodeName().startsWith("xmlns:")) {
                /* A document created from a dom4j document using dom4j 1.6.1's io.domWriter
                 does this ?!
                 attr.getNodeName(): xmlns:w 
                 attr.getNamespaceURI(): null
                 attr.getLocalName(): null
                 attr.getPrefix(): null
                         
                 unless i'm doing something wrong, this is another reason to
                 remove use of dom4j from docx4j
                */
                ;
                // this is a namespace declaration. not our problem
            } else if (attr.getNamespaceURI() == null) {
                //log.debug("attr.getLocalName(): " + attr.getLocalName() + "=" + attr.getValue());
                ((org.w3c.dom.Element) newChild).setAttribute(attr.getName(), attr.getValue());
            } else if (attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")) {
                ; // this is a namespace declaration. not our problem
            } else if (attr.getNodeName() != null) {
                // && attr.getNodeName().equals("xml:space")) {
                // restrict this fix to xml:space only, if necessary

                // Necessary when invoked from BindingTraverserXSLT,
                // com.sun.org.apache.xerces.internal.dom.AttrNSImpl
                // otherwise it was becoming w:space="preserve"!

                /* eg xml:space
                 * 
                   attr.getNodeName(): xml:space
                   attr.getNamespaceURI(): http://www.w3.org/XML/1998/namespace
                   attr.getLocalName(): space
                   attr.getPrefix(): xml
                 */

                ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getNodeName(),
                        attr.getValue());
            } else {
                ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getLocalName(),
                        attr.getValue());
            }
        }

        // recurse on each child
        NodeList children = sourceNode.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                //treeCopy( (DTMNodeProxy)children.item(i), newChild);
                treeCopy((Node) children.item(i), newChild);
            }
        }

        break;

    case Node.TEXT_NODE:

        // Where destParent is com.sun.org.apache.xerces.internal.dom.DocumentImpl,
        // destParent.getOwnerDocument() returns null.
        // #document ; com.sun.org.apache.xerces.internal.dom.DocumentImpl

        //               System.out.println(sourceNode.getNodeValue());

        //System.out.println(destParent.getNodeName() + " ; " + destParent.getClass().getName() );
        if (destParent.getOwnerDocument() == null && destParent.getNodeName().equals("#document")) {
            Node textNode = ((Document) destParent).createTextNode(sourceNode.getNodeValue());
            destParent.appendChild(textNode);
        } else {
            Node textNode = destParent.getOwnerDocument().createTextNode(sourceNode.getNodeValue());
            // Warning: If you attempt to write a single "&" character, it will be converted to &amp; 
            // even if it doesn't look like that with getNodeValue() or getTextContent()!
            // So avoid any tricks with entities! See notes in docx2xhtmlNG2.xslt
            Node appended = destParent.appendChild(textNode);

        }
        break;

    //                case Node.CDATA_SECTION_NODE:
    //                    writer.write("<![CDATA[" +
    //                                 node.getNodeValue() + "]]>");
    //                    break;
    //
    //                case Node.COMMENT_NODE:
    //                    writer.write(indentLevel + "<!-- " +
    //                                 node.getNodeValue() + " -->");
    //                    writer.write(lineSeparator);
    //                    break;
    //
    //                case Node.PROCESSING_INSTRUCTION_NODE:
    //                    writer.write("<?" + node.getNodeName() +
    //                                 " " + node.getNodeValue() +
    //                                 "?>");
    //                    writer.write(lineSeparator);
    //                    break;
    //
    //                case Node.ENTITY_REFERENCE_NODE:
    //                    writer.write("&" + node.getNodeName() + ";");
    //                    break;
    //
    //                case Node.DOCUMENT_TYPE_NODE:
    //                    DocumentType docType = (DocumentType)node;
    //                    writer.write("<!DOCTYPE " + docType.getName());
    //                    if (docType.getPublicId() != null)  {
    //                        System.out.print(" PUBLIC \"" +
    //                            docType.getPublicId() + "\" ");
    //                    } else {
    //                        writer.write(" SYSTEM ");
    //                    }
    //                    writer.write("\"" + docType.getSystemId() + "\">");
    //                    writer.write(lineSeparator);
    //                    break;
    }
}

From source file:org.exist.dom.ElementImpl.java

private Node appendChild(Txn transaction, NodeId newNodeId, NodeImplRef last, NodePath lastPath, Node child,
        StreamListener listener) throws DOMException {
    if (last == null || last.getNode() == null)
    //TODO : same test as above ? -pb
    {//from w ww .  ja v  a  2  s  .c  o  m
        throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "invalid node");
    }
    final DocumentImpl owner = (DocumentImpl) getOwnerDocument();
    DBBroker broker = null;
    try {
        broker = ownerDocument.getBrokerPool().get(null);
        switch (child.getNodeType()) {
        case Node.DOCUMENT_FRAGMENT_NODE:
            appendChildren(transaction, newNodeId, null, last, lastPath, child.getChildNodes(), listener);
            return null; // TODO: implement document fragments so
        //we can return all newly appended children
        case Node.ELEMENT_NODE:
            // create new element
            final ElementImpl elem = new ElementImpl(
                    new QName(child.getLocalName() == null ? child.getNodeName() : child.getLocalName(),
                            child.getNamespaceURI(), child.getPrefix()),
                    broker.getBrokerPool().getSymbols());
            elem.setNodeId(newNodeId);
            elem.setOwnerDocument(owner);
            final NodeListImpl ch = new NodeListImpl();
            final NamedNodeMap attribs = child.getAttributes();
            int numActualAttribs = 0;
            for (int i = 0; i < attribs.getLength(); i++) {
                final Attr attr = (Attr) attribs.item(i);
                if (!attr.getNodeName().startsWith("xmlns")) {
                    ch.add(attr);
                    numActualAttribs++;
                } else {
                    final String xmlnsDecl = attr.getNodeName();
                    final String prefix = xmlnsDecl.length() == 5 ? "" : xmlnsDecl.substring(6);
                    elem.addNamespaceMapping(prefix, attr.getNodeValue());
                }
            }
            final NodeList cl = child.getChildNodes();
            for (int i = 0; i < cl.getLength(); i++) {
                final Node n = cl.item(i);
                if (n.getNodeType() != Node.ATTRIBUTE_NODE) {
                    ch.add(n);
                }
            }
            elem.setChildCount(ch.getLength());
            if (numActualAttribs != (short) numActualAttribs) {
                throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "Too many attributes");
            }
            elem.setAttributes((short) numActualAttribs);
            lastPath.addComponent(elem.getQName());
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), elem);
            broker.indexNode(transaction, elem, lastPath);
            broker.getIndexController().indexNode(transaction, elem, lastPath, listener);
            elem.setChildCount(0);
            last.setNode(elem);
            //process child nodes
            elem.appendChildren(transaction, newNodeId.newChild(), null, last, lastPath, ch, listener);
            broker.endElement(elem, lastPath, null);
            broker.getIndexController().endElement(transaction, elem, lastPath, listener);
            lastPath.removeLastComponent();
            return elem;
        case Node.TEXT_NODE:
            final TextImpl text = new TextImpl(newNodeId, ((Text) child).getData());
            text.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), text);
            broker.indexNode(transaction, text, lastPath);
            broker.getIndexController().indexNode(transaction, text, lastPath, listener);
            last.setNode(text);
            return text;
        case Node.CDATA_SECTION_NODE:
            final CDATASectionImpl cdata = new CDATASectionImpl(newNodeId, ((CDATASection) child).getData());
            cdata.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), cdata);
            broker.indexNode(transaction, cdata, lastPath);
            last.setNode(cdata);
            return cdata;
        case Node.ATTRIBUTE_NODE:
            final Attr attr = (Attr) child;
            final String ns = attr.getNamespaceURI();
            final String prefix = (Namespaces.XML_NS.equals(ns) ? "xml" : attr.getPrefix());
            String name = attr.getLocalName();
            if (name == null) {
                name = attr.getName();
            }
            final QName attrName = new QName(name, ns, prefix);
            final AttrImpl attrib = new AttrImpl(attrName, attr.getValue(),
                    broker.getBrokerPool().getSymbols());
            attrib.setNodeId(newNodeId);
            attrib.setOwnerDocument(owner);
            if (ns != null && attrName.compareTo(Namespaces.XML_ID_QNAME) == Constants.EQUAL) {
                // an xml:id attribute. Normalize the attribute and set its type to ID
                attrib.setValue(StringValue.trimWhitespace(StringValue.collapseWhitespace(attrib.getValue())));
                attrib.setType(AttrImpl.ID);
            } else {
                attrName.setNameType(ElementValue.ATTRIBUTE);
            }
            broker.insertNodeAfter(transaction, last.getNode(), attrib);
            broker.indexNode(transaction, attrib, lastPath);
            broker.getIndexController().indexNode(transaction, attrib, lastPath, listener);
            last.setNode(attrib);
            return attrib;
        case Node.COMMENT_NODE:
            final CommentImpl comment = new CommentImpl(((Comment) child).getData());
            comment.setNodeId(newNodeId);
            comment.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), comment);
            broker.indexNode(transaction, comment, lastPath);
            last.setNode(comment);
            return comment;
        case Node.PROCESSING_INSTRUCTION_NODE:
            final ProcessingInstructionImpl pi = new ProcessingInstructionImpl(newNodeId,
                    ((ProcessingInstruction) child).getTarget(), ((ProcessingInstruction) child).getData());
            pi.setOwnerDocument(owner);
            //insert the node
            broker.insertNodeAfter(transaction, last.getNode(), pi);
            broker.indexNode(transaction, pi, lastPath);
            last.setNode(pi);
            return pi;
        default:
            throw new DOMException(DOMException.INVALID_MODIFICATION_ERR,
                    "Unknown node type: " + child.getNodeType() + " " + child.getNodeName());
        }
    } catch (final EXistException e) {
        LOG.warn("Exception while appending node: " + e.getMessage(), e);
    } finally {
        if (broker != null)
            broker.release();
    }
    return null;
}

From source file:org.getobjects.appserver.templates.WOxElemBuilder.java

public WOAssociation associationForAttribute(Attr _attr) {
    if (_attr == null)
        return null;

    /* get namespace */

    String ns = _attr.getNamespaceURI();
    if (ns == null)
        ns = ""; /* this will get the default */

    /* map namespace to Class */

    Class assocClass = nsToAssocClass.get(ns);
    if (assocClass == null)
        assocClass = nsToAssocClass.get("");
    if (assocClass == null) {
        this.log.error("could not find association class: " + _attr);
        return null;
    }/*w  w w .  ja va  2 s.  c  o  m*/

    /* construct */

    WOAssociation assoc = (WOAssociation) NSJavaRuntime.NSAllocateObject(assocClass, String.class,
            _attr.getValue());

    return assoc;
}

From source file:org.jboss.bpm.console.server.util.DOMUtils.java

/** Copy attributes between elements
 *//*from w w  w . j  a va  2s  .  c  o  m*/
public static void copyAttributes(Element destElement, Element srcElement) {
    NamedNodeMap attribs = srcElement.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        Attr attr = (Attr) attribs.item(i);
        String uri = attr.getNamespaceURI();
        String qname = attr.getName();
        String value = attr.getNodeValue();

        // Prevent DOMException: NAMESPACE_ERR: An attempt is made to create or
        // change an object in a way which is incorrect with regard to namespaces.
        if (uri == null && qname.startsWith("xmlns")) {
            log.trace("Ignore attribute: [uri=" + uri + ",qname=" + qname + ",value=" + value + "]");
        } else {
            destElement.setAttributeNS(uri, qname, value);
        }
    }
}

From source file:org.mule.config.spring.parsers.assembly.DefaultBeanAssembler.java

/**
 * Add a property defined by an attribute to the bean we are constructing.
 *
 * <p>Since an attribute value is always a string, we don't have to deal with complex types
 * here - the only issue is whether or not we have a reference.  References are detected
 * by explicit annotation or by the "-ref" at the end of an attribute name.  We do not
 * check the Spring repo to see if a name already exists since that could lead to
 * unpredictable behaviour.//from   w ww  .  j  a  v a  2s.  co  m
 * (see {@link org.mule.config.spring.parsers.assembly.configuration.PropertyConfiguration})
 * @param attribute The attribute to add
 */
public void extendBean(Attr attribute) {
    AbstractBeanDefinition beanDefinition = bean.getBeanDefinition();
    String oldName = SpringXMLUtils.attributeName(attribute);
    String oldValue = attribute.getNodeValue();
    if (attribute.getNamespaceURI() == null) {
        if (!beanConfig.isIgnored(oldName)) {
            logger.debug(attribute + " for " + beanDefinition.getBeanClassName());
            String newName = bestGuessName(beanConfig, oldName, beanDefinition.getBeanClassName());
            Object newValue = beanConfig.translateValue(oldName, oldValue);
            addPropertyWithReference(beanDefinition.getPropertyValues(), beanConfig.getSingleProperty(oldName),
                    newName, newValue);
        }
    } else if (isAnnotationsPropertyAvailable(beanDefinition.getBeanClass())) {
        //Add attribute defining namespace as annotated elements. No reconciliation is done here ie new values override old ones.
        QName name;
        if (attribute.getPrefix() != null) {
            name = new QName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix());
        } else {
            name = new QName(attribute.getNamespaceURI(), attribute.getLocalName());
        }
        Object value = beanConfig.translateValue(oldName, oldValue);
        addAnnotationValue(beanDefinition.getPropertyValues(), name, value);
        MuleContext muleContext = MuleApplicationContext.getCurrentMuleContext().get();
        if (muleContext != null) {
            Map<QName, Set<Object>> annotations = muleContext.getConfigurationAnnotations();
            Set<Object> values = annotations.get(name);
            if (values == null) {
                values = new HashSet<Object>();
                annotations.put(name, values);
            }
            values.add(value);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot assign " + beanDefinition.getBeanClass() + " to " + AnnotatedObject.class);
        }
    }
}

From source file:org.omg.bpmn.miwg.util.xml.diff.AbstractXmlDifferenceListener.java

/**
 * Vendors may introduce new namespaces and these should not be reported as
 * significant differences./*w  ww. j a  v a2  s . co m*/
 * 
 * @param difference
 * @return
 * @see https://github.com/bpmn-miwg/bpmn-miwg-tools/issues/13
 */
protected boolean isCausedByAdditionalNamespace(Difference difference) {
    try {
        Attr attr = null;
        int len = difference.getTestNodeDetail().getNode().getAttributes().getLength();
        for (int i = 0; i < len; i++) {
            Attr tmp = (Attr) difference.getTestNodeDetail().getNode().getAttributes().item(i);
            if (difference.getTestNodeDetail().getValue().equals(tmp.getLocalName())) {
                // this is the attribute in question
                attr = tmp;
                break;
            }
        }

        if (attr != null) {
            String uri = attr.getNamespaceURI();
            if (uri != null && difference.getControlNodeDetail().getNode().getOwnerDocument()
                    .lookupNamespaceURI(uri) == null) {
                // So the control document does not have this namespace
                // that the test doc does => OK to ignore.
                return true;
            }
        }
    } catch (NullPointerException e) {
        // Assume because the namespace scenario we are looking for is
        // not cause of difference and report it
    }

    return false;
}

From source file:org.openestate.io.core.XmlUtils.java

private static void printNode(Element node, int indent) {
    String prefix = (indent > 0) ? StringUtils.repeat(">", indent) + " " : "";
    LOGGER.debug(prefix + "<" + node.getTagName() + "> / " + node.getNamespaceURI() + " / " + node.getPrefix());

    prefix = StringUtils.repeat(">", indent + 1) + " ";
    NamedNodeMap attribs = node.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        Attr attrib = (Attr) attribs.item(i);
        LOGGER.debug(prefix + "@" + attrib.getName() + " / " + attrib.getNamespaceURI() + " / "
                + attrib.getPrefix());/*w  w  w . j a  v a 2s  . c o  m*/
    }
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child instanceof Element) {
            XmlUtils.printNode((Element) child, indent + 1);
        }
    }
}

From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java

License:asdf

/**
 * Verifica se os atributos so iguais. Existe pois a comparao de
 * atributos possui particularidades./*from  w w w. j a va 2s  .c  o  m*/
 *
 * @param n1 -
 * @param n2 -
 * @throws Exception Se no forem iguais
 */
public static void isIgual(Attr n1, Attr n2) throws Exception {
    if (n1 == n2) {
        return;
    }
    isIgual(n1, n2, "NodeName", n1.getNodeName(), n2.getNodeName());
    isIgual(n1, n2, "NodeValue", n1.getNodeValue(), n2.getNodeValue());

    //Por algum motivo depois do parse Prefix passa de null para no null
    //isIgual(n1, n2, "Prefix", n1.getPrefix(), n2.getPrefix());
    //Por algum motivo depois do parse Localname passe de no null para
    // null
    //isIgual(n1, n2, "LocalName", n1.getLocalName(), n2.getLocalName());

    if (!(n1.getNodeName().startsWith("xmlns") && n2.getNodeName().startsWith("xmlns"))) {
        isIgual(n1, n2, "Namespace", n1.getNamespaceURI(), n2.getNamespaceURI());
    }
}