Example usage for org.w3c.dom Node getAttributes

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

Introduction

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

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:de.mpg.imeji.presentation.metadata.extractors.BasicExtractor.java

static void displayMetadata(List<String> techMd, Node node, int level) {
    StringBuffer sb = new StringBuffer();
    // print open tag of element
    indent(techMd, sb, level);/*from   ww  w.j a v a 2  s  .  c om*/
    sb.append("<" + node.getNodeName());
    NamedNodeMap map = node.getAttributes();
    if (map != null) {
        // print attribute values
        int length = map.getLength();
        for (int i = 0; i < length; i++) {
            Node attr = map.item(i);
            sb.append(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
        }
    }
    Node child = node.getFirstChild();
    if (child == null) {
        // no children, so close element and return
        sb.append("/>");
        techMd.add(sb.toString());
        sb.delete(0, sb.length());
        return;
    }
    // children, so close current tag
    sb.append(">");
    techMd.add(sb.toString());
    sb.delete(0, sb.length());
    while (child != null) {
        // print children recursively
        displayMetadata(techMd, child, level + 1);
        child = child.getNextSibling();
    }
    // print close tag of element
    indent(techMd, sb, level);
    sb.append("</" + node.getNodeName() + ">");
    techMd.add(sb.toString());
    sb.delete(0, sb.length());
}

From source file:Main.java

/**
 * Format generated xml doc by indentation
 *
 * @param node   For java, rather than GWT
 * @param indent//w  ww  .  j a  v  a  2 s .  c o  m
 * @return
 */
public static String format(Node node, String indent) {
    StringBuilder formatted = new StringBuilder();

    if (node.getNodeType() == Node.ELEMENT_NODE) {
        StringBuilder attributes = new StringBuilder();
        for (int k = 0; k < node.getAttributes().getLength(); k++) {
            attributes.append(" ");
            attributes.append(node.getAttributes().item(k).getNodeName());
            attributes.append("=\"");
            attributes.append(node.getAttributes().item(k).getNodeValue());
            attributes.append("\"");
        }

        formatted.append(indent);
        formatted.append("<");
        formatted.append(node.getNodeName());
        formatted.append(attributes.toString());
        if (!node.hasChildNodes()) {
            formatted.append("/>\n");
            return formatted.toString();
        }
        if ((node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE)) {
            formatted.append(">");
        } else {
            formatted.append(">\n");
        }

        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            formatted.append(format(node.getChildNodes().item(i), indent + "   "));
        }

        if (node.hasChildNodes() && node.getFirstChild().getNodeType() != Node.TEXT_NODE) {
            formatted.append(indent);
        }
        formatted.append("</");
        formatted.append(node.getNodeName());
        formatted.append(">\n");
    } else {
        String value = node.getTextContent().trim();
        if (value.length() > 0) {
            formatted.append(value);
        }
    }
    return formatted.toString();
}

From source file:Main.java

/**
 * Convenience method to copy the contents of the old {@link Node} into the
 * new one./*from  w  ww . j ava  2  s. c  o  m*/
 * 
 * @param newDoc
 * @param newNode
 * @param oldParent
 */
public static void copyContents(Document newDoc, Node newNode, Node oldNode) {
    // FIXME we should be able to achieve this with much less code (e.g.
    // the code commented out) but for some reason there are
    // incompatibility issues being spat out by the tests.
    //      final NodeList childNodes = oldNode.getChildNodes();
    //        for (int i = 0; i < childNodes.getLength(); i++) {
    //           final Node child = newDoc.importNode(childNodes.item(i), true);
    //           newNode.appendChild(child);
    //        }

    final NodeList childs = oldNode.getChildNodes();

    for (int i = 0; i < childs.getLength(); i++) {
        final Node child = childs.item(i);
        Element newElem = null;
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE:
            //Get all the attributes of an element in a map
            final NamedNodeMap attrs = child.getAttributes();

            // Process each attribute
            newElem = newDoc.createElement(child.getNodeName());
            for (int j = 0; j < attrs.getLength(); j++) {
                final Attr attr = (Attr) attrs.item(j);
                // add attribute name and value to the new element
                newElem.setAttribute(attr.getNodeName(), attr.getNodeValue());
            }
            newNode.appendChild(newElem);
            break;

        case Node.TEXT_NODE:
            newNode.appendChild(newDoc.createTextNode(getString(child)));
        }
        copyContents(newDoc, newElem, child);
    }
}

From source file:Main.java

/**
 * Copy one node to another node.// www  .  java  2s . c om
 * @param source source Node
 * @param dest destination Node
 * @return destination Node
 */
public static synchronized Node copyNode(Node source, Node dest) {
    if (source.getNodeType() == Node.TEXT_NODE) {
        Text tn = dest.getOwnerDocument().createTextNode(source.getNodeValue());
        return tn;
    }

    Node attr = null;
    NamedNodeMap attrs = source.getAttributes();

    if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
            attr = attrs.item(i);
            ((Element) dest).setAttribute(attr.getNodeName(), attr.getNodeValue());
        }
    }

    Node child = null;
    NodeList list = source.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        child = list.item(i);
        if (!(child instanceof Text)) {
            Element en = dest.getOwnerDocument().createElementNS(child.getNamespaceURI(), child.getNodeName());

            if (child.getNodeValue() != null) {
                en.setNodeValue(child.getNodeValue());
            }

            Node n = copyNode(child, en);
            dest.appendChild(n);
        } else if (child instanceof CDATASection) {
            CDATASection cd = dest.getOwnerDocument().createCDATASection(child.getNodeValue());
            dest.appendChild(cd);
        } else {
            Text tn = dest.getOwnerDocument().createTextNode(child.getNodeValue());
            dest.appendChild(tn);
        }
    }
    return dest;
}

From source file:com.enioka.jqm.tools.ResourceParser.java

private static void importXml() throws NamingException {
    InputStream is = ResourceParser.class.getClassLoader().getResourceAsStream(Helpers.resourceFile);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    try {/* ww w. j ava2 s.c  om*/
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("resource");

        String jndiAlias = null, resourceClass = null, description = "no description", scope = null,
                auth = "Container", factory = null;
        boolean singleton = false;

        for (int i = 0; i < nList.getLength(); i++) {
            Node n = nList.item(i);
            Map<String, String> otherParams = new HashMap<String, String>();

            NamedNodeMap attrs = n.getAttributes();
            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr = attrs.item(j);
                String key = attr.getNodeName();
                String value = attr.getNodeValue();

                if ("name".equals(key)) {
                    jndiAlias = value;
                } else if ("type".equals(key)) {
                    resourceClass = value;
                } else if ("description".equals(key)) {
                    description = value;
                } else if ("factory".equals(key)) {
                    factory = value;
                } else if ("auth".equals(key)) {
                    auth = value;
                } else if ("singleton".equals(key)) {
                    singleton = Boolean.parseBoolean(value);
                } else {
                    otherParams.put(key, value);
                }
            }

            if (resourceClass == null || jndiAlias == null || factory == null) {
                throw new NamingException("could not load the resource.xml file");
            }

            JndiResourceDescriptor jrd = new JndiResourceDescriptor(resourceClass, description, scope, auth,
                    factory, singleton);
            for (Map.Entry<String, String> prm : otherParams.entrySet()) {
                jrd.add(new StringRefAddr(prm.getKey(), prm.getValue()));
            }
            xml.put(jndiAlias, jrd);
        }
    } catch (Exception e) {
        NamingException pp = new NamingException("could not initialize the JNDI local resources");
        pp.setRootCause(e);
        throw pp;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:CB_Core.GCVote.GCVote.java

public static ArrayList<RatingData> GetRating(String User, String password, ArrayList<String> Waypoints) {
    ArrayList<RatingData> result = new ArrayList<RatingData>();

    String data = "userName=" + User + "&password=" + password + "&waypoints=";
    for (int i = 0; i < Waypoints.size(); i++) {
        data += Waypoints.get(i);/*from   w  w w  .jav  a 2  s.co m*/
        if (i < (Waypoints.size() - 1))
            data += ",";
    }

    try {
        HttpPost httppost = new HttpPost("http://gcvote.de/getVotes.php");

        httppost.setEntity(new ByteArrayEntity(data.getBytes("UTF8")));

        // Log.info(log, "GCVOTE-Post" + data);

        // Execute HTTP Post Request
        String responseString = Execute(httppost);

        // Log.info(log, "GCVOTE-Response" + responseString);

        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(responseString));

        Document doc = db.parse(is);

        NodeList nodelist = doc.getElementsByTagName("vote");

        for (Integer i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);

            RatingData ratingData = new RatingData();
            ratingData.Rating = Float.valueOf(node.getAttributes().getNamedItem("voteAvg").getNodeValue());
            String userVote = node.getAttributes().getNamedItem("voteUser").getNodeValue();
            ratingData.Vote = (userVote == "") ? 0 : Float.valueOf(userVote);
            ratingData.Waypoint = node.getAttributes().getNamedItem("waypoint").getNodeValue();
            result.add(ratingData);

        }

    } catch (Exception e) {
        String Ex = "";
        if (e != null) {
            if (e != null && e.getMessage() != null)
                Ex = "Ex = [" + e.getMessage() + "]";
            else if (e != null && e.getLocalizedMessage() != null)
                Ex = "Ex = [" + e.getLocalizedMessage() + "]";
            else
                Ex = "Ex = [" + e.toString() + "]";
        }
        Log.err(log, "GcVote-Error" + Ex);
        return null;
    }
    return result;

}

From source file:Main.java

/**
 * @param n1 first Node to test/*  w w w  .j  a  va 2s  .  co m*/
 * @param n2 second Node to test
 * @return true if a deep compare show the same children and attributes in
 * the same order
 */
public static boolean equals(Node n1, Node n2) {
    // compare type
    if (!n1.getNodeName().equals(n2.getNodeName())) {
        return false;
    }
    // compare attributes
    NamedNodeMap nnm1 = n1.getAttributes();
    NamedNodeMap nnm2 = n2.getAttributes();
    if (nnm1.getLength() != nnm2.getLength()) {
        return false;
    }
    for (int i = 0; i < nnm1.getLength(); i++) {
        Node attr1 = nnm1.item(i);
        if (!getAttribute(n1, attr1.getNodeName()).equals(getAttribute(n2, attr1.getNodeName()))) {
            return false;
        }
    }
    // compare children
    Node c1 = n1.getFirstChild();
    Node c2 = n2.getFirstChild();
    for (;;) {
        while ((c1 != null) && c1.getNodeName().startsWith("#")) {
            c1 = c1.getNextSibling();
        }
        while ((c2 != null) && c2.getNodeName().startsWith("#")) {
            c2 = c2.getNextSibling();
        }
        if ((c1 == null) && (c2 == null)) {
            break;
        }
        if ((c1 == null) || (c2 == null)) {
            return false;
        }
        if (!equals(c1, c2)) {
            return false;
        }
        c1 = c1.getNextSibling();
        c2 = c2.getNextSibling();
    }
    return true;
}

From source file:LVCoref.MMAX2.java

public static Boolean addMmaxNeAnnotation(Document d, String annotation_filename) {
    try {// w  w w .  ja va 2  s .c o  m
        File mmax_file = new File(annotation_filename);
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        org.w3c.dom.Document doc = dBuilder.parse(mmax_file);
        NodeList markables = doc.getElementsByTagName("markable");

        for (int i = 0; i < markables.getLength(); i++) {
            org.w3c.dom.Node markable = markables.item(i);

            String span = markable.getAttributes().getNamedItem("span").getNodeValue();
            String category = markable.getAttributes().getNamedItem("category").getNodeValue();

            String[] intervals = span.split(",");
            String[] interval = intervals[0].split("\\.\\.");
            int start = Integer.parseInt(interval[0].substring(5)) - 1;
            int end = start;
            if (interval.length > 1) {
                end = Integer.parseInt(interval[1].substring(5)) - 1;
            }
            //System.err.println(i+" :" + start+ "-"+end);
            //                if (category.equals("profession")) category = "person";
            //                if (category.equals("event")) continue;
            //                //if (category.equals("product")) continue;
            //                if (category.equals("media")) continue;
            //                if (category.equals("time")) continue;
            //                if (category.equals("sum")) continue;

            if (category.equals("other"))
                continue;
            if (d.getNode(start).ne_annotation.length() != 0 || d.getNode(start).ne_annotation.length() != 0)
                continue;

            //if (d.getNode(start).isProperByFirstLetter()) {
            for (int j = start; j <= end; j++) {
                //System.out.println(j);
                Node q = d.getNode(j);
                q.ne_annotation = category;
            }
            //}
        }
    } catch (Exception e) {
        System.err.println("Error adding MMAX2 annotation:" + e.getMessage());
        return false;
    }
    return true;
}

From source file:net.codjo.dataprocess.server.treatmenthelper.TreatmentHelper.java

public static void insertRepositoryContent(Connection con, int repositoryId, String content)
        throws SQLException, TreatmentException, TransformerException {
    Document doc;//from w  w w.ja v a 2 s  .  c  o  m
    try {
        doc = XMLUtils.parse(content);
    } catch (Exception ex) {
        throw new TreatmentException(ex);
    }
    PreparedStatement pStmt = con.prepareStatement(
            "insert into PM_REPOSITORY_CONTENT (REPOSITORY_CONTENT_ID, REPOSITORY_ID, TREATMENT_ID, CONTENT) values (?, ?, ?, ?)");
    try {
        NodeList nodes = doc.getElementsByTagName(DataProcessConstants.TREATMENT_ENTITY_XML);
        int nbNodes = nodes.getLength();
        for (int i = 0; i < nbNodes; i++) {
            Node node = nodes.item(i);
            String treatmentId = node.getAttributes().getNamedItem("id").getNodeValue();
            if (treatmentId.length() > 50) {
                throw new TreatmentException("La taille de l'identifiant d'un traitement ('" + treatmentId
                        + "') dpasse 50 caractres.");
            }

            String contentNode = XMLUtils.nodeToString(node);
            pStmt.setInt(1, SQLUtil.getNextId(con, "PM_REPOSITORY_CONTENT", "REPOSITORY_CONTENT_ID"));
            pStmt.setInt(2, repositoryId);
            pStmt.setString(3, treatmentId);
            pStmt.setString(4, contentNode);
            pStmt.executeUpdate();
        }
    } finally {
        pStmt.close();
    }
}

From source file:Main.java

private static void printNote(NodeList nodeList, int depth) {
    for (int count = 0; count < nodeList.getLength(); count++) {
        Node tempNode = nodeList.item(count);
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
            System.out.println(depth + "Node Name =" + tempNode.getNodeName());
            System.out.println(depth + "Node Value =" + tempNode.getTextContent());
            if (tempNode.hasAttributes()) {
                NamedNodeMap nodeMap = tempNode.getAttributes();
                for (int i = 0; i < nodeMap.getLength(); i++) {
                    Node node = nodeMap.item(i);
                    System.out.println("attr name : " + node.getNodeName());
                    System.out.println("attr value : " + node.getNodeValue());
                }/*w w w .  j av  a 2 s  .  c  o  m*/
            }
            if (tempNode.hasChildNodes()) {
                printNote(tempNode.getChildNodes(), depth + 1);
            }
            System.out.println(depth + "Node Name =" + tempNode.getNodeName());
        }
    }
}