Example usage for org.w3c.dom Attr getNodeValue

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

Introduction

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

Prototype

public String getNodeValue() throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:org.erdc.cobie.shared.spreadsheetml.transformation.cobietab.COBieSpreadSheet.java

License:asdf

public static void nodeToStream(Node node, PrintWriter out) {
    String workSheetName = "";
    boolean canonical = false;
    // is there anything to do?
    if (node == null) {
        return;//  ww  w  .  j a  va2  s .  co m
    }

    int type = node.getNodeType();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        if (!canonical) {
            out.println("<?xml version=\"1.0\"?>");
        }
        // print(((Document)node).getDocumentElement());

        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            nodeToStream(children.item(iChild), out);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            if (((node.getNodeName().equalsIgnoreCase("Worksheet")
                    || node.getNodeName().equalsIgnoreCase("ss:Worksheet"))
                    && attr.getName().equalsIgnoreCase("Name")) || attr.getName().equalsIgnoreCase("ss:Name")) {
                workSheetName = normalize(attr.getNodeValue());
            }
            out.print(' ');
            out.print(attr.getNodeName());
            out.print("=\"");
            out.print(normalize(attr.getNodeValue()));
            out.print('"');
        }
        out.print('>');
        out.flush();
        NodeList children = node.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                nodeToStream(children.item(i), out);
            }
        }
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    nodeToStream(children.item(i), out);
                }
            }
        } else {
            out.print('&');
            out.print(node.getNodeName());
            out.print(';');
        }
        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        if (canonical) {
            out.print(normalize(node.getNodeValue()));
        } else {
            out.print("<![CDATA[");
            out.print(node.getNodeValue());
            out.print("]]>");
        }
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String data = node.getNodeValue();
        if ((data != null) && (data.length() > 0)) {
            out.print(' ');
            out.print(data);
        }
        out.print("?>");
        break;
    }

    // print comment
    case Node.COMMENT_NODE: {
        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");
        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if ((node.getNodeName().equalsIgnoreCase("Worksheet")
                || node.getNodeName().equalsIgnoreCase("ss:Worksheet")) && (workSheetName.length() > 0)) {
            out.print(printCOBieSheetDataValidation(workSheetName));
        }
        out.print("</");
        out.print(node.getNodeName());
        out.print('>');
    }

    out.flush();

}

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
    {/*w w  w.  j a v a  2s. c om*/
        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.jboss.bpm.console.server.util.DOMUtils.java

/** Get the attributes as Map<QName, String>
 */// w  w  w.j  a  va  2s. co  m
public static Map getAttributes(Element el) {
    Map attmap = new HashMap();
    NamedNodeMap attribs = el.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        Attr attr = (Attr) attribs.item(i);
        String name = attr.getName();
        QName qname = resolveQName(el, name);
        String value = attr.getNodeValue();
        attmap.put(qname, value);
    }
    return attmap;
}

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

/** Copy attributes between elements
 *//*from   www.ja v a  2s .co  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 ww  w  .  j a va  2 s  . c  om*/
 * (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.mule.config.spring.parsers.assembly.DefaultBeanAssembler.java

/**
 * Add a property defined by an attribute to the parent of the bean we are constructing.
 *
 * <p>This is unusual.  Normally you want {@link #extendBean(org.w3c.dom.Attr)}.
 * @param attribute The attribute to add
 *//*from   w  w w . j  a  v  a  2 s.co m*/
public void extendTarget(Attr attribute) {
    String oldName = SpringXMLUtils.attributeName(attribute);
    String oldValue = attribute.getNodeValue();
    String newName = bestGuessName(targetConfig, oldName, bean.getBeanDefinition().getBeanClassName());
    Object newValue = targetConfig.translateValue(oldName, oldValue);
    addPropertyWithReference(target.getPropertyValues(), targetConfig.getSingleProperty(oldName), newName,
            newValue);
}

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.// ww  w. j  a  va  2 s. 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());
    }
}

From source file:org.viafirma.util.OfflineResolver.java

/**
 * Method engineResolve/*from ww w  .ja v a 2  s.  c om*/
 *
 * @param uri
 * @param BaseURI
 *
 * @throws ResourceResolverException
 */
@SuppressWarnings("cast")
@Override
public XMLSignatureInput engineResolve(Attr uri, String BaseURI) throws ResourceResolverException {

    try {
        String URI = uri.getNodeValue();

        if (OfflineResolver._uriMap.containsKey(URI)) {
            String newURI = (String) OfflineResolver._uriMap.get(URI);

            log.debug("Mapped " + URI + " to " + newURI);

            InputStream is = new FileInputStream(newURI);

            log.debug("Available bytes = " + is.available());

            XMLSignatureInput result = new XMLSignatureInput(is);

            // XMLSignatureInput result = new XMLSignatureInput(inputStream);
            result.setSourceURI(URI);
            result.setMIMEType((String) OfflineResolver._mimeMap.get(URI));

            return result;
        } else {
            Object exArgs[] = { "The URI " + URI + " is not configured for offline work" };

            throw new ResourceResolverException("generic.EmptyMessage", exArgs, uri, BaseURI);
        }
    } catch (IOException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, BaseURI);
    }
}

From source file:org.viafirma.util.OfflineResolver.java

/**
 * We resolve http URIs <I>without</I> fragment...
 *
 * @param uri/*w w  w . java 2  s  .c  om*/
 * @param BaseURI
 *
 */
@Override
public boolean engineCanResolve(Attr uri, String BaseURI) {

    String uriNodeValue = uri.getNodeValue();

    if (uriNodeValue.equals("") || uriNodeValue.startsWith("#")) {
        return false;
    }

    try {
        URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue());

        if (uriNew.getScheme().equals("http")) {
            log.debug("I state that I can resolve " + uriNew.toString());

            return true;
        }

        log.debug("I state that I can't resolve " + uriNew.toString());
    } catch (URI.MalformedURIException ex) {
    }

    return false;
}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * process the given node/*  www.j a v  a 2  s . c  om*/
 *
 * @param node Node to process
 * @param procNode The procedure node
 *
 * @return keep going
 *
 * @throws Throwable On badness
 */
protected boolean processTagCall(Element node, Element procNode) throws Throwable {
    if (procNode == null) {
        return error("Could not find procedure node for call:" + XmlUtil.toString(node));
    }

    pushProperties();
    String cdata = XmlUtil.getChildText(node);
    if ((cdata != null) && (cdata.trim().length() > 0)) {
        putProperty("paramtext", cdata);
    } else {
        putProperty("paramtext", "");
    }

    NamedNodeMap procnnm = procNode.getAttributes();
    if (procnnm != null) {
        for (int i = 0; i < procnnm.getLength(); i++) {
            Attr attr = (Attr) procnnm.item(i);
            if (!ATTR_NAME.equals(attr.getNodeName())) {
                putProperty(attr.getNodeName(), applyMacros(attr.getNodeValue()));
            }
        }
    }

    NamedNodeMap nnm = node.getAttributes();
    if (nnm != null) {
        for (int i = 0; i < nnm.getLength(); i++) {
            Attr attr = (Attr) nnm.item(i);
            if (!ATTR_NAME.equals(attr.getNodeName())) {
                putProperty(attr.getNodeName(), applyMacros(attr.getNodeValue()));
            }
        }
    }
    try {
        if (!processChildren(node)) {
            return false;
        }
        try {
            if (!processChildren(procNode)) {
                return false;
            }
        } catch (MyReturnException mre) {
            //noop
        }
    } catch (Throwable throwable) {
        popProperties();
        throw throwable;
    }
    popProperties();
    return true;
}