Example usage for org.w3c.dom NamedNodeMap getLength

List of usage examples for org.w3c.dom NamedNodeMap getLength

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getLength.

Prototype

public int getLength();

Source Link

Document

The number of nodes in this map.

Usage

From source file:org.focusns.common.web.page.config.xml.XmlPageFactory.java

private Map<String, String> getParameters(Element pageEle) {
    Map<String, String> parameters = new HashMap<String, String>();
    NamedNodeMap nnm = pageEle.getAttributes();
    for (int i = 0; i < nnm.getLength(); i++) {
        Node node = nnm.item(i);/*from www  .  j  ava2  s .c o  m*/
        String paramName = node.getNodeName();
        String paramValue = node.getNodeValue();
        parameters.put(paramName, paramValue);
    }
    return parameters;
}

From source file:eu.europa.esig.dss.validation.report.SimpleReport.java

private List<Conclusion.BasicInfo> getBasicInfo(final String signatureId, final String basicInfoType) {

    final List<XmlDom> elementList = getElements("/SimpleReport/Signature[@Id='%s']/" + basicInfoType,
            signatureId);//from  www  . j  a  v  a  2  s  .  co m
    final List<Conclusion.BasicInfo> infoList = new ArrayList<Conclusion.BasicInfo>();
    for (final XmlDom infoElement : elementList) {

        Conclusion.BasicInfo basicInfo = new Conclusion.BasicInfo(basicInfoType);
        basicInfo.setValue(infoElement.getText());
        final NamedNodeMap attributes = infoElement.getAttributes();
        for (int index = 0; index < attributes.getLength(); index++) {

            final Node attribute = attributes.item(index);
            basicInfo.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
        }
        infoList.add(basicInfo);
    }
    return infoList;
}

From source file:com.ryantenney.metrics.spring.reporter.AbstractReporterElementParser.java

protected void addDefaultProperties(Element element, BeanDefinitionBuilder beanDefBuilder) {
    final Map<String, String> properties = new HashMap<String, String>();
    final NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        final Node attribute = attributes.item(i);
        final String name = attribute.getNodeName();
        if (name.equals(METRIC_REGISTRY_REF) || name.equals(ID) || name.equals(TYPE)) {
            continue;
        }// ww w . java2s .c  om
        properties.put(name, attribute.getNodeValue());
    }

    validate(properties);

    beanDefBuilder.addPropertyReference("metricRegistry", element.getAttribute(METRIC_REGISTRY_REF));
    beanDefBuilder.addPropertyValue("properties", properties);
}

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentTrimmer.java

public void processElement(final Element element) throws IOException {
    final NodeList nodeList = element.getChildNodes();
    for (int index = nodeList.getLength() - 1; index >= 0; index--) {
        final Node node = nodeList.item(index);
        if (node instanceof Element) {
            final Element lookup = (Element) node;

            if ("script".equals(lookup.getTagName())) {
                // REMOVE script tag.
                element.removeChild(node);
                continue;
            }/*from   w  w w .  jav a 2  s  . c o m*/

            if ("noscript".equals(lookup.getTagName())) {
                // REMOVE noscript tag.
                element.removeChild(node);
                continue;
            }

            if ("iframe".equals(lookup.getTagName())) {
                final NamedNodeMap nnm = lookup.getAttributes();
                for (int indexNnm = 0; indexNnm < nnm.getLength(); indexNnm++) {
                    final Attr attr = (Attr) nnm.item(indexNnm);

                    // System.out.println(" " + attr.getName() + " [" +
                    // attr.getValue() + "]");
                    if ("style".equals(attr.getName())) {
                        final String value = attr.getValue().replaceAll(" ", "");
                        if (value.indexOf("display:none") >= 0) {
                            // REMOVE iframe tag which is display:none
                            // style..
                            element.removeChild(node);
                            continue;
                        }
                    }
                }
            }

            processElement(lookup);
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLSerializer.java

private void toXml(final int indent, final DomNode node, final StringBuilder buffer) {
    final String nodeName = node.getNodeName();
    buffer.append('<').append(nodeName);

    final String optionalPrefix = "";
    final String namespaceURI = node.getNamespaceURI();
    final String prefix = node.getPrefix();
    if (namespaceURI != null && prefix != null) {
        boolean sameNamespace = false;
        for (DomNode parentNode = node
                .getParentNode(); parentNode instanceof DomElement; parentNode = parentNode.getParentNode()) {
            if (namespaceURI.equals(parentNode.getNamespaceURI())) {
                sameNamespace = true;//w  w w .j av a2s .c o  m
            }
        }
        if (node.getParentNode() == null || !sameNamespace) {
            ((DomElement) node).setAttribute("xmlns:" + prefix, namespaceURI);
        }
    }

    final NamedNodeMap attributesMap = node.getAttributes();
    for (int i = 0; i < attributesMap.getLength(); i++) {
        final DomAttr attrib = (DomAttr) attributesMap.item(i);
        buffer.append(' ').append(attrib.getQualifiedName()).append('=').append('"').append(attrib.getValue())
                .append('"');
    }
    boolean startTagClosed = false;
    for (final DomNode child : node.getChildren()) {
        if (!startTagClosed) {
            buffer.append(optionalPrefix).append('>');
            startTagClosed = true;
        }
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE:
            toXml(indent + 1, child, buffer);
            break;

        case Node.TEXT_NODE:
            String value = child.getNodeValue();
            value = StringUtils.escapeXmlChars(value);
            if (preserveWhiteSpace_) {
                buffer.append(value.replace("\n", "\r\n"));
            } else if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
                buffer.append("\r\n");
                final DomNode sibling = child.getNextSibling();
                if (sibling != null && sibling.getNodeType() == Node.ELEMENT_NODE) {
                    for (int i = 0; i < indent; i++) {
                        buffer.append('\t');
                    }
                }
            } else {
                buffer.append(value.replace("\n", "\r\n"));
            }
            break;

        case Node.CDATA_SECTION_NODE:
        case Node.COMMENT_NODE:
            if (!preserveWhiteSpace_ && buffer.charAt(buffer.length() - 1) == '\n') {
                for (int i = 0; i < indent; i++) {
                    buffer.append('\t');
                }
            }
            buffer.append(child.asXml());
            break;

        default:

        }
    }
    if (!startTagClosed) {
        buffer.append(optionalPrefix).append("/>");
    } else {
        if (!preserveWhiteSpace_ && buffer.charAt(buffer.length() - 1) == '\n') {
            for (int i = 0; i < indent - 1; i++) {
                buffer.append('\t');
            }
        }
        buffer.append('<').append('/').append(nodeName).append('>');
    }
}

From source file:de.micromata.genome.gwiki.page.impl.wiki.rte.els.RteTableDomElementListener.java

@Override
public boolean listen(DomElementEvent event) {
    GWikiWikiParserContext parseContext = event.getParseContext();
    if (event.getElementName().equals("TABLE") == true) {
        GWikiFragment frag;//from  www.j  a  va  2 s.  co  m
        NamedNodeMap attrs = event.element.getAttributes();
        if (attrs.getLength() == 0
                || (attrs.getLength() == 1 && event.getStyleClass().equals("gwikiTable") == true)) {
            frag = new GWikiFragmentTable();
        } else {
            frag = convertToBodyMacro(event,
                    GWikiMacroRenderFlags.combine(GWikiMacroRenderFlags.NewLineAfterStart,
                            GWikiMacroRenderFlags.NewLineBeforeEnd, GWikiMacroRenderFlags.TrimTextContent));
        }
        tableStack.push(frag);
        List<GWikiFragment> childs = event.walkCollectChilds();
        addChildren(frag, childs);
        tableStack.pop();
        frag = checkConvertTable(frag, event);
        parseContext.addFragment(frag);
        return false;
    }
    if (event.getElementName().equals("TBODY") == true) {
        List<GWikiFragment> childs = event.walkCollectChilds();
        parseContext.addFragments(childs);
        return false;
    }

    if (event.getElementName().equals("TR") == true) {
        GWikiFragment top = tableStack.peek();
        if (top instanceof GWikiFragmentTable) {
            GWikiFragmentTable table = (GWikiFragmentTable) top;
            GWikiFragmentTable.Row row = new GWikiFragmentTable.Row();
            copyAttributes(row.getAttributes(), event);
            table.addRow(row);
            event.walkCollectChilds();
        } else if (top instanceof GWikiMacroFragment) {
            GWikiMacroFragment frag = convertToBodyMacro(event, 0);
            parseContext.addFragment(frag);
            List<GWikiFragment> childs = event.walkCollectChilds();
            frag.addChilds(childs);
        }
        return false;

    }
    if (event.getElementName().equals("TH") == true || event.getElementName().equals("TD") == true) {
        GWikiFragment top = tableStack.peek();
        if (top instanceof GWikiFragmentTable) {
            String en = event.getElementName().toLowerCase();
            GWikiFragmentTable table = (GWikiFragmentTable) top;
            GWikiFragmentTable.Cell cell = table.addCell(en);
            copyAttributes(cell.getAttributes(), event);
            List<GWikiFragment> childs = event.walkCollectChilds();
            table.addCellContent(childs);
        } else {
            GWikiMacroFragment frag = convertToBodyMacro(event, 0);
            parseContext.addFragment(frag);
            List<GWikiFragment> childs = event.walkCollectChilds();
            frag.addChilds(childs);

        }
    }
    return false;
}

From source file:com.amalto.core.storage.record.XmlDOMDataRecordReader.java

private void _read(MetadataRepository repository, DataRecord dataRecord, ComplexTypeMetadata type,
        Element element) {/*from   ww  w.j a  v a 2 s  . com*/
    // TODO Don't use getChildNodes() but getNextSibling() calls (but cause regressions -> see TMDM-5410).
    String tagName = element.getTagName();
    NodeList children = element.getChildNodes();
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (!type.hasField(attribute.getNodeName())) {
            continue;
        }
        FieldMetadata field = type.getField(attribute.getNodeName());
        dataRecord.set(field, StorageMetadataUtils.convert(attribute.getNodeValue(), field));
    }
    for (int i = 0; i < children.getLength(); i++) {
        Node currentChild = children.item(i);
        if (currentChild instanceof Element) {
            Element child = (Element) currentChild;
            if (METADATA_NAMESPACE.equals(child.getNamespaceURI())) {
                DataRecordMetadataHelper.setMetadataValue(dataRecord.getRecordMetadata(), child.getLocalName(),
                        child.getTextContent());
            } else {
                if (!type.hasField(child.getTagName())) {
                    continue;
                }
                FieldMetadata field = type.getField(child.getTagName());
                if (field.getType() instanceof ContainedComplexTypeMetadata) {
                    ComplexTypeMetadata containedType = (ComplexTypeMetadata) field.getType();
                    String xsiType = child.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); //$NON-NLS-1$
                    if (xsiType.startsWith("java:")) { //$NON-NLS-1$
                        // Special format for 'java:' type names (used in Castor XML to indicate actual class name)
                        xsiType = ClassRepository.format(StringUtils
                                .substringAfterLast(StringUtils.substringAfter(xsiType, "java:"), ".")); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    if (!xsiType.isEmpty()) {
                        for (ComplexTypeMetadata subType : containedType.getSubTypes()) {
                            if (subType.getName().equals(xsiType)) {
                                containedType = subType;
                                break;
                            }
                        }
                    }
                    DataRecord containedRecord = new DataRecord(containedType,
                            UnsupportedDataRecordMetadata.INSTANCE);
                    dataRecord.set(field, containedRecord);
                    _read(repository, containedRecord, containedType, child);
                } else if (ClassRepository.EMBEDDED_XML.equals(field.getType().getName())) {
                    try {
                        dataRecord.set(field, Util.nodeToString(element));
                    } catch (TransformerException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    _read(repository, dataRecord, type, child);
                }
            }
        } else if (currentChild instanceof Text) {
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < element.getChildNodes().getLength(); j++) {
                String nodeValue = element.getChildNodes().item(j).getNodeValue();
                if (nodeValue != null) {
                    builder.append(nodeValue.trim());
                }
            }
            String textContent = builder.toString();
            if (!textContent.isEmpty()) {
                FieldMetadata field = type.getField(tagName);
                if (field instanceof ReferenceFieldMetadata) {
                    ComplexTypeMetadata actualType = ((ReferenceFieldMetadata) field).getReferencedType();
                    String mdmType = element.getAttributeNS(SkipAttributeDocumentBuilder.TALEND_NAMESPACE,
                            "type"); //$NON-NLS-1$
                    if (!mdmType.isEmpty()) {
                        actualType = repository.getComplexType(mdmType);
                    }
                    if (actualType == null) {
                        throw new IllegalArgumentException("Type '" + mdmType + "' does not exist.");
                    }
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, actualType));
                } else {
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, type));
                }
            }
        }
    }
}

From source file:fi.csc.kapaVirtaAS.MessageTransformer.java

private Stream<Node> namedNodeMapToStream(NamedNodeMap namedNodeMap) {
    return IntStream.range(0, namedNodeMap.getLength()).mapToObj(namedNodeMap::item);
}

From source file:XMLDocumentWriter.java

/**
 * Output the specified DOM Node object, printing it using the specified
 * indentation string//ww w  .  ja  v a 2s  . com
 */
public void write(Node node, String indent) {
    // The output depends on the type of the node
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE: { // If its a Document node
        Document doc = (Document) node;
        out.println(indent + "<?xml version='1.0'?>"); // Output header
        Node child = doc.getFirstChild(); // Get the first node
        while (child != null) { // Loop 'till no more nodes
            write(child, indent); // Output node
            child = child.getNextSibling(); // Get next node
        }
        break;
    }
    case Node.DOCUMENT_TYPE_NODE: { // It is a <!DOCTYPE> tag
        DocumentType doctype = (DocumentType) node;
        // Note that the DOM Level 1 does not give us information about
        // the the public or system ids of the doctype, so we can't output
        // a complete <!DOCTYPE> tag here. We can do better with Level 2.
        out.println("<!DOCTYPE " + doctype.getName() + ">");
        break;
    }
    case Node.ELEMENT_NODE: { // Most nodes are Elements
        Element elt = (Element) node;
        out.print(indent + "<" + elt.getTagName()); // Begin start tag
        NamedNodeMap attrs = elt.getAttributes(); // Get attributes
        for (int i = 0; i < attrs.getLength(); i++) { // Loop through them
            Node a = attrs.item(i);
            out.print(" " + a.getNodeName() + "='" + // Print attr. name
                    fixup(a.getNodeValue()) + "'"); // Print attr. value
        }
        out.println(">"); // Finish start tag

        String newindent = indent + "    "; // Increase indent
        Node child = elt.getFirstChild(); // Get child
        while (child != null) { // Loop
            write(child, newindent); // Output child
            child = child.getNextSibling(); // Get next child
        }

        out.println(indent + "</" + // Output end tag
                elt.getTagName() + ">");
        break;
    }
    case Node.TEXT_NODE: { // Plain text node
        Text textNode = (Text) node;
        String text = textNode.getData().trim(); // Strip off space
        if ((text != null) && text.length() > 0) // If non-empty
            out.println(indent + fixup(text)); // print text
        break;
    }
    case Node.PROCESSING_INSTRUCTION_NODE: { // Handle PI nodes
        ProcessingInstruction pi = (ProcessingInstruction) node;
        out.println(indent + "<?" + pi.getTarget() + " " + pi.getData() + "?>");
        break;
    }
    case Node.ENTITY_REFERENCE_NODE: { // Handle entities
        out.println(indent + "&" + node.getNodeName() + ";");
        break;
    }
    case Node.CDATA_SECTION_NODE: { // Output CDATA sections
        CDATASection cdata = (CDATASection) node;
        // Careful! Don't put a CDATA section in the program itself!
        out.println(indent + "<" + "![CDATA[" + cdata.getData() + "]]" + ">");
        break;
    }
    case Node.COMMENT_NODE: { // Comments
        Comment c = (Comment) node;
        out.println(indent + "<!--" + c.getData() + "-->");
        break;
    }
    default: // Hopefully, this won't happen too much!
        System.err.println("Ignoring node: " + node.getClass().getName());
        break;
    }
}

From source file:br.com.elotech.sits.service.AbstractService.java

public Node getXSDNotaFiscal(File file) throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);/*from  w  w  w.  j  a  va 2s  . c o  m*/
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(file);

    Node root = (Node) doc.getDocumentElement();

    NamedNodeMap attributes = root.getAttributes();
    if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
            Node node = attributes.item(i);
            if (node.getNodeType() == Node.ATTRIBUTE_NODE) {

                if (ATRIBUTO_PRINCIPAL_NOTA_FISCAL.equals(node.getNodeName())) {
                    return node;
                }
            }
        }
    }

    return null;

}