Example usage for org.w3c.dom Node ATTRIBUTE_NODE

List of usage examples for org.w3c.dom Node ATTRIBUTE_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node ATTRIBUTE_NODE.

Prototype

short ATTRIBUTE_NODE

To view the source code for org.w3c.dom Node ATTRIBUTE_NODE.

Click Source Link

Document

The node is an Attr.

Usage

From source file:de.betterform.xml.xforms.model.Instance.java

public static ModelItem createModelItem(Node node) {
    String id = Model.generateModelItemId();
    ModelItem modelItem;/*from   w  w w  .  jav a2  s .c o  m*/
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        modelItem = new XercesElementImpl(id);
    } else {
        modelItem = new XercesNodeImpl(id);
    }
    modelItem.setNode(node);

    Node parentNode;
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        parentNode = ((Attr) node).getOwnerElement();
    } else {
        parentNode = node.getParentNode();
    }
    if (parentNode != null) {
        ModelItem parentItem = (ModelItem) parentNode.getUserData("");
        if (parentItem == null) {
            parentItem = createModelItem(parentNode);
        }

        modelItem.setParent(parentItem);
    }

    node.setUserData("", modelItem, null);
    return modelItem;
}

From source file:jef.tools.XMLUtils.java

private static void output(Node node, StreamResult sr, String encoding, int indent, Boolean XmlDeclarion)
        throws IOException {
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        sr.getWriter().write(node.getNodeValue());
        sr.getWriter().flush();/*w w w .j  a v  a 2 s  . c  om*/
        return;
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;
    try {
        if (indent > 0) {
            try {
                tf.setAttribute("indent-number", indent);
                t = tf.newTransformer();
                // ?XML??XML?
                t.setOutputProperty(OutputKeys.INDENT, "yes");
            } catch (Exception e) {
            }
        } else {
            t = tf.newTransformer();
        }

        t.setOutputProperty(OutputKeys.METHOD, "xml");
        if (encoding != null) {
            t.setOutputProperty(OutputKeys.ENCODING, encoding);
        }
        if (XmlDeclarion == null) {
            XmlDeclarion = (node instanceof Document);
        }
        if (node instanceof Document) {
            Document doc = (Document) node;
            if (doc.getDoctype() != null) {
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC,
                        doc.getDoctype().getPublicId());
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM,
                        doc.getDoctype().getSystemId());
            }
        }
        if (XmlDeclarion) {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        } else {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
    } catch (Exception tce) {
        throw new IOException(tce);
    }
    DOMSource doms = new DOMSource(node);
    try {
        t.transform(doms, sr);
    } catch (TransformerException te) {
        IOException ioe = new IOException();
        ioe.initCause(te);
        throw ioe;
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

public static String getNodeText(Node node) {
    if (node == null) {
        return null;
    } else if (node.getNodeType() == Node.TEXT_NODE) {
        return ((Text) node).getData();
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        return ((Attr) node).getValue();
    } else {//from   w  w w . jav a 2 s.  c  om
        return getElementText((Element) node);
    }
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private SOAPElement addSoapElement(Context context, SOAPEnvelope se, SOAPElement soapParent, Node node)
        throws Exception {
    String prefix = node.getPrefix();
    String namespace = node.getNamespaceURI();
    String nodeName = node.getNodeName();
    String localName = node.getLocalName();
    String value = node.getNodeValue();

    boolean includeResponseElement = true;
    if (context.sequenceName != null) {
        includeResponseElement = ((Sequence) context.requestedObject).isIncludeResponseElement();
    }//  www . j  av  a  2s .com

    SOAPElement soapElement = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        boolean toAdd = true;
        if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
            toAdd = false;
        }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(element.getParentNode().getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/".equals(namespace)
                || nodeName.toLowerCase().endsWith(":envelope") || nodeName.toLowerCase().endsWith(":body")
        //element.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 ||
        //nodeName.toUpperCase().indexOf("NS0:") != -1
        ) {
            toAdd = false;
        }

        if (toAdd) {
            if (prefix == null || prefix.equals("")) {
                soapElement = soapParent.addChildElement(nodeName);
            } else {
                soapElement = soapParent.addChildElement(se.createName(localName, prefix, namespace));
            }
        } else {
            soapElement = soapParent;
        }

        if (soapElement != null) {
            if (soapParent.equals(se.getBody()) && !soapParent.equals(soapElement)) {
                if (XsdForm.qualified == context.project.getSchemaElementForm()) {
                    if (soapElement.getAttribute("xmlns") == null) {
                        soapElement.addAttribute(se.createName("xmlns"), context.project.getTargetNamespace());
                    }
                }
            }

            if (element.hasAttributes()) {
                String attrType = element.getAttribute("type");
                if (("attachment").equals(attrType)) {
                    if (context.requestedObject instanceof AbstractHttpTransaction) {
                        AttachmentDetails attachment = AttachmentManager.getAttachment(element);
                        if (attachment != null) {
                            byte[] raw = attachment.getData();
                            if (raw != null)
                                soapElement.addTextNode(Base64.encodeBase64String(raw));
                        }

                        /* DON'T WORK YET *\
                        AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), element.getAttribute("content-type"));
                        ap.setContentId(key);
                        ap.setContentLocation(element.getAttribute("url"));
                        responseMessage.addAttachmentPart(ap);
                        \* DON'T WORK YET */
                    }
                }

                if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
                    // do not add attributes
                } else {
                    NamedNodeMap attributes = element.getAttributes();
                    int len = attributes.getLength();
                    for (int i = 0; i < len; i++) {
                        Node item = attributes.item(i);
                        addSoapElement(context, se, soapElement, item);
                    }
                }
            }

            if (element.hasChildNodes()) {
                NodeList childNodes = element.getChildNodes();
                int len = childNodes.getLength();
                for (int i = 0; i < len; i++) {
                    Node item = childNodes.item(i);
                    switch (item.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        addSoapElement(context, se, soapElement, item);
                        break;
                    case Node.CDATA_SECTION_NODE:
                    case Node.TEXT_NODE:
                        String text = item.getNodeValue();
                        text = (text == null) ? "" : text;
                        soapElement.addTextNode(text);
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        if (prefix == null || prefix.equals("")) {
            soapElement = soapParent.addAttribute(se.createName(nodeName), value);
        } else {
            soapElement = soapParent.addAttribute(se.createName(localName, prefix, namespace), value);
        }
    }
    return soapElement;
}

From source file:com.enonic.esl.xml.XMLTool.java

/**
 * Retrieve a text from an element or attribute using an xpath expression.
 *
 * @param contextElement The root element that the xpath expression is to be applied on.
 * @param xpath          The xpath that selects the element or attribute containing the text.
 * @return The element text./*  w w  w.j  a v a  2  s. c  o m*/
 */

public static String getElementText(Element contextElement, String xpath) {

    if (contextElement == null) {
        return null;
    }

    Node node = selectNode(contextElement, xpath);

    if (node != null) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            return ((Text) node).getData();
        } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            return ((Attr) node).getValue();
        } else {
            return getElementText((Element) node);
        }
    }

    return null;
}

From source file:de.betterform.xml.xforms.model.Instance.java

private void listModelItems(List list, Node node, boolean deep) {
    ModelItem modelItem = (ModelItem) node.getUserData("");
    if (modelItem == null) {
        modelItem = createModelItem(node);
    }// ww  w.  ja  va2 s  .  co  m
    list.add(modelItem);

    if (deep) {
        NamedNodeMap attributes = node.getAttributes();
        for (int index = 0; attributes != null && index < attributes.getLength(); index++) {
            listModelItems(list, attributes.item(index), deep);
        }
        if (node.getNodeType() != Node.ATTRIBUTE_NODE) {
            NodeList children = node.getChildNodes();
            for (int index = 0; index < children.getLength(); index++) {
                listModelItems(list, children.item(index), deep);
            }
        }
    }
}

From source file:com.connexta.arbitro.ctx.xacml3.XACML3EvaluationCtx.java

private Set<String> getChildXPaths(Node root, String xPath) {

    Set<String> xPaths = new HashSet<String>();
    NamespaceContext namespaceContext = null;

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    if (namespaceContext == null) {

        //see if the request root is in a namespace
        String namespace = null;//from w w  w . j av a  2s  .c o m
        if (root != null) {
            namespace = root.getNamespaceURI();
        }
        // name spaces are used, so we need to lookup the correct
        // prefix to use in the search string
        NamedNodeMap namedNodeMap = root.getAttributes();

        Map<String, String> nsMap = new HashMap<String, String>();
        if (namedNodeMap != null) {
            for (int i = 0; i < namedNodeMap.getLength(); i++) {
                Node n = namedNodeMap.item(i);
                // we found the matching namespace, so get the prefix
                // and then break out
                String prefix = DOMHelper.getLocalName(n);
                String nodeValue = n.getNodeValue();
                nsMap.put(prefix, nodeValue);
            }
        }

        // if there is not any namespace is defined for content element, default XACML request
        //  name space would be there.
        if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) {
            nsMap.put("xacml", namespace);
        }

        namespaceContext = new DefaultNamespaceContext(nsMap);
    }

    xpath.setNamespaceContext(namespaceContext);

    try {
        XPathExpression expression = xpath.compile(xPath);
        NodeList matches = (NodeList) expression.evaluate(root, XPathConstants.NODESET);
        if (matches != null && matches.getLength() > 0) {

            for (int i = 0; i < matches.getLength(); i++) {
                String text = null;
                Node node = matches.item(i);
                short nodeType = node.getNodeType();

                // see if this is straight text, or a node with data under
                // it and then get the values accordingly
                if ((nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.COMMENT_NODE)
                        || (nodeType == Node.TEXT_NODE) || (nodeType == Node.ATTRIBUTE_NODE)) {
                    // there is no child to this node
                    text = node.getNodeValue();
                } else {

                    // the data is in a child node
                    text = "/" + DOMHelper.getLocalName(node);
                }
                String newXPath = '(' + xPath + ")[" + (i + 1) + ']';
                xPaths.add(newXPath);
            }
        }
    } catch (Exception e) {
        // TODO
    }

    return xPaths;
}

From source file:dk.netarkivet.harvester.harvesting.WARCWriterProcessor.java

/**
 * Return relevant values as header-like fields (here ANVLRecord, but spec-defined "application/warc-fields" type
 * when written). Field names from from DCMI Terms and the WARC/0.17 specification.
 *
 * @see org.archive.crawler.framework.WriterPoolProcessor#getFirstrecordBody(java.io.File)
 *///from  www .  ja  v a  2  s .  c  om
@Override
protected String getFirstrecordBody(File orderFile) {
    ANVLRecord record = new ANVLRecord(7);
    record.addLabelValue("software", "Heritrix/" + Heritrix.getVersion() + " http://crawler.archive.org");

    try {
        InetAddress host = InetAddress.getLocalHost();
        record.addLabelValue("ip", host.getHostAddress());
        record.addLabelValue("hostname", host.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.log(Level.WARNING, "unable top obtain local crawl engine host", e);
    }

    // conforms to ISO 28500:2009 as of May 2009
    // as described at http://bibnum.bnf.fr/WARC/
    // latest draft as of November 2008
    record.addLabelValue("format", "WARC File Format 1.0");
    record.addLabelValue("conformsTo", "http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf");

    // Get other values from order.xml
    try {
        Document doc = XmlUtils.getDocument(orderFile);
        addIfNotBlank(record, "operator", XmlUtils.xpathOrNull(doc, "//meta/operator"));
        addIfNotBlank(record, "publisher", XmlUtils.xpathOrNull(doc, "//meta/organization"));
        addIfNotBlank(record, "audience", XmlUtils.xpathOrNull(doc, "//meta/audience"));
        addIfNotBlank(record, "isPartOf", XmlUtils.xpathOrNull(doc, "//meta/name"));

        // disabling "created" field per HER-1634
        // though it's theoretically useful as a means of distinguishing
        // one crawl from another, the current usage/specification is too
        // vague... in particular a 'created' field in the 'warcinfo' is
        // reasonable to interpret as applying to the WARC-unit, rather
        // than the crawl-job-unit so we remove it and see if anyone
        // complains or makes a case for restoring it in a less-ambiguous
        // manner
        // String rawDate = XmlUtils.xpathOrNull(doc,"//meta/date");
        // if(StringUtils.isNotBlank(rawDate)) {
        // Date date;
        // try {
        // date = ArchiveUtils.parse14DigitDate(rawDate);
        // addIfNotBlank(record,"created",ArchiveUtils.getLog14Date(date));
        // } catch (ParseException e) {
        // logger.log(Level.WARNING,"obtaining warc created date",e);
        // }
        // }

        addIfNotBlank(record, "description", XmlUtils.xpathOrNull(doc, "//meta/description"));
        addIfNotBlank(record, "robots",
                XmlUtils.xpathOrNull(doc, "//newObject[@name='robots-honoring-policy']/string[@name='type']"));
        addIfNotBlank(record, "http-header-user-agent",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='user-agent']"));
        addIfNotBlank(record, "http-header-from",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='from']"));
        if (metadataMap == null) {
            //metadataMap = getMetadataItems();
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(H1HeritrixTemplate.METADATA_ITEMS_XPATH);
            Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
            //NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            //Node node = nodeList.item(0);
            if (node != null) {
                NodeList nodeList = node.getChildNodes();
                if (nodeList != null) {
                    metadataMap = new HashMap();
                    for (int i = 0; i < nodeList.getLength(); ++i) {
                        node = nodeList.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            String typeName = node.getNodeName();
                            if ("string".equals(typeName)) {
                                Node attribute = node.getAttributes().getNamedItem("name");
                                if (attribute != null && attribute.getNodeType() == Node.ATTRIBUTE_NODE) {
                                    String key = attribute.getNodeValue();
                                    if (key != null && key.length() > 0) {
                                        String value = node.getTextContent();
                                        metadataMap.put(key, value);
                                        // debug
                                        //System.out.println(key + "=" + value);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, "Error obtaining warcinfo", e);
    } catch (XPathExpressionException e) {
        logger.log(Level.WARNING, "Error obtaining metadata items", e);
    }

    // add fields from harvesInfo.xml version 0.4
    /*
     * <harvestInfo> <version>0.4</version> <jobId>1</jobId> <priority>HIGHPRIORITY</priority>
     * <harvestNum>0</harvestNum> <origHarvestDefinitionID>1</origHarvestDefinitionID>
     * <maxBytesPerDomain>500000000</maxBytesPerDomain> <maxObjectsPerDomain>2000</maxObjectsPerDomain>
     * <orderXMLName>default_orderxml</orderXMLName>
     * <origHarvestDefinitionName>netarkivet</origHarvestDefinitionName> <scheduleName>Once_a_week</scheduleName>
     * <harvestFilenamePrefix>1-1</harvestFilenamePrefix> <jobSubmitDate>Some date</jobSubmitDate>
     * <performer>undefined</performer> </harvestInfo>
     */
    String netarchiveSuiteComment = "#added by NetarchiveSuite "
            + dk.netarkivet.common.Constants.getVersionString();
    ANVLRecord recordNAS = new ANVLRecord(7);

    if (metadataMap != null) {
        // Add the data from the metadataMap to the WarcInfoRecord.
        recordNAS.addLabelValue(HARVESTINFO_VERSION, (String) metadataMap.get(HARVESTINFO_VERSION));
        recordNAS.addLabelValue(HARVESTINFO_JOBID, (String) metadataMap.get(HARVESTINFO_JOBID));
        recordNAS.addLabelValue(HARVESTINFO_CHANNEL, (String) metadataMap.get(HARVESTINFO_CHANNEL));
        recordNAS.addLabelValue(HARVESTINFO_HARVESTNUM, (String) metadataMap.get(HARVESTINFO_HARVESTNUM));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONID,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONID));
        recordNAS.addLabelValue(HARVESTINFO_MAXBYTESPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXBYTESPERDOMAIN));

        recordNAS.addLabelValue(HARVESTINFO_MAXOBJECTSPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXOBJECTSPERDOMAIN));
        recordNAS.addLabelValue(HARVESTINFO_ORDERXMLNAME, (String) metadataMap.get(HARVESTINFO_ORDERXMLNAME));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONNAME,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONNAME));

        if (metadataMap.containsKey((HARVESTINFO_SCHEDULENAME))) {
            recordNAS.addLabelValue(HARVESTINFO_SCHEDULENAME,
                    (String) metadataMap.get(HARVESTINFO_SCHEDULENAME));
        }
        recordNAS.addLabelValue(HARVESTINFO_HARVESTFILENAMEPREFIX,
                (String) metadataMap.get(HARVESTINFO_HARVESTFILENAMEPREFIX));

        recordNAS.addLabelValue(HARVESTINFO_JOBSUBMITDATE, (String) metadataMap.get(HARVESTINFO_JOBSUBMITDATE));

        if (metadataMap.containsKey(HARVESTINFO_PERFORMER)) {
            recordNAS.addLabelValue(HARVESTINFO_PERFORMER, (String) metadataMap.get(HARVESTINFO_PERFORMER));
        }

        if (metadataMap.containsKey(HARVESTINFO_AUDIENCE)) {
            recordNAS.addLabelValue(HARVESTINFO_AUDIENCE, (String) metadataMap.get(HARVESTINFO_AUDIENCE));
        }
    } else {
        logger.log(Level.SEVERE, "Error missing metadata");
    }

    // really ugly to return as string, when it may just be merged with
    // a couple other fields at write time, but changing would require
    // larger refactoring
    return record.toString() + netarchiveSuiteComment + "\n" + recordNAS.toString();
}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * returns a canonical XPath locationpath for a given Node. Each step in the path will contain the positional
 * predicate of the Element. Example '/root[1]/a[1]/b[2]/c[5]/@d'. This would point to<br/>
 * to Attribute named 'd'<br/>//  ww w .  j  a  v  a  2s  .co m
 * on 5th Element 'c"<br/>
 * on 2nd Element 'b'<br/>
 * on first Element a<br/>
 * which is a child of the Document Element.
 *
 * @param node the Node where to start
 * @return canonical XPath locationPath for given Node or the empty string if node is null
 */
public static String getCanonicalPath(Node node) {

    if (node == null) {
        return "";
    }

    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        return "/";
    }

    //add ourselves
    String canonPath;
    String ns = node.getNamespaceURI();
    String nodeName1 = node.getNodeName();
    String nodeName2 = node.getLocalName();
    if (ns != null && ns.equals("http://www.w3.org/1999/xhtml")
            && node.getNodeName().equals(node.getLocalName())) {
        canonPath = "html:" + node.getNodeName();
    } else {
        canonPath = node.getNodeName();
    }
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        canonPath = "@" + canonPath;
    } else if (node.getNodeType() == Node.ELEMENT_NODE) {
        int position = DOMUtil.getCurrentNodesetPosition(node);
        //append position if we are an Element
        canonPath += "[" + position + "]";
    }

    //check for parent - if there's none we're root
    Node parent = null;
    if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.TEXT_NODE) {
        parent = node.getParentNode();
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        parent = ((Attr) node).getOwnerElement();
    }
    if (parent == null) {
        parent = node.getOwnerDocument().getDocumentElement();
    }
    if (parent.getNodeType() == Node.DOCUMENT_NODE || parent.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) {
        canonPath = "/" + canonPath;
    } else {
        canonPath = DOMUtil.getCanonicalPath(parent) + "/" + canonPath;
    }

    return canonPath;
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static String getValueForMatch(XmlCursor cursor) {
    Node domNode = cursor.getDomNode();
    String stringValue;//from  w  w w .j  a  v a  2  s. co m

    if (domNode.getNodeType() == Node.ATTRIBUTE_NODE || domNode.getNodeType() == Node.TEXT_NODE) {
        stringValue = domNode.getNodeValue();
    } else if (cursor.getObject() instanceof XmlAnySimpleType) {
        stringValue = ((XmlAnySimpleType) cursor.getObject()).getStringValue();
    } else {
        if (domNode.getNodeType() == Node.ELEMENT_NODE) {
            Element elm = (Element) domNode;
            if (elm.getChildNodes().getLength() == 1 && !hasContentAttributes(elm)) {
                stringValue = getElementText(elm);
            } else {
                stringValue = cursor.getObject().xmlText(
                        new XmlOptions().setSavePrettyPrint().setSaveOuter().setSaveAggressiveNamespaces());
            }
        } else {
            stringValue = domNode.getNodeValue();
        }
    }
    return stringValue;
}