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:it.osm.gtfs.input.OSMParser.java

public static List<Stop> readOSMStops(String fileName)
        throws ParserConfigurationException, SAXException, IOException {
    List<Stop> result = new ArrayList<Stop>();
    Multimap<String, Stop> refBuses = HashMultimap.create();
    Multimap<String, Stop> refRails = HashMultimap.create();

    File file = new File(fileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();

    NodeList nodeLst = doc.getElementsByTagName("node");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        Stop st = new Stop(null, null,
                Double.valueOf(fstNode.getAttributes().getNamedItem("lat").getNodeValue()),
                Double.valueOf(fstNode.getAttributes().getNamedItem("lon").getNodeValue()), null);
        st.originalXMLNode = fstNode;/*from  www . j  a v a2s.  c  o m*/
        NodeList att = fstNode.getChildNodes();
        for (int t = 0; t < att.getLength(); t++) {
            Node attNode = att.item(t);
            if (attNode.getAttributes() != null) {
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("ref"))
                    st.setCode(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("name"))
                    st.setName(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("gtfs_id"))
                    st.setGtfsId(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("highway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("bus_stop"))
                    st.setIsRailway(false);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("tram_stop"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("station"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("public_transport")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("stop_position")
                        && st.isRailway() == null)
                    st.setIsStopPosition(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("train")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("tram")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("bus")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(false);
            }
        }

        if (st.isRailway() == null)
            if (st.isStopPosition())
                continue; //ignore unsupported stop positions (like ferries)
            else
                throw new IllegalArgumentException("Unknow node type for node: " + st.getOSMId()
                        + ". We support only highway=bus_stop, public_transport=stop_position, railway=tram_stop and railway=station");

        //Check duplicate ref in osm
        if (st.getCode() != null) {
            if (st.isStopPosition() == null || st.isStopPosition() == false) {
                if (st.isRailway()) {
                    if (refRails.containsKey(st.getCode())) {
                        for (Stop existingStop : refRails.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }

                    refRails.put(st.getCode(), st);
                } else {
                    if (refBuses.containsKey(st.getCode())) {
                        for (Stop existingStop : refBuses.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }
                    refBuses.put(st.getCode(), st);
                }
            }
        }
        result.add(st);
    }

    return result;
}

From source file:Main.java

public static void printNode(Node node, String indent) {
    String nodeName = node.getNodeName();
    System.out.print(indent);/*from   ww w  . j  a  v  a 2s . co  m*/

    if (nodeName.equals("#text")) {
        String nodeText = node.getNodeValue();

        if ((nodeText != null) && (nodeText.trim().length() > 0)) {
            System.out.print(nodeText.trim());
        }
    } else {
        System.out.print(nodeName);
    }

    System.out.print(" ");

    if (!nodeName.equals("#text")) {
        NamedNodeMap attrs = node.getAttributes();

        if (attrs != null) {
            for (int i = 0; i < attrs.getLength(); i++) {
                Node attr = attrs.item(i);
                System.out.print(attr.getNodeName() + "=\"" + attr.getNodeValue() + "\" ");
            }
        }
    }

    NodeList children = node.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
        System.out.println();
        printNode(children.item(i), indent + "\t");
    }
}

From source file:Main.java

private static void printNote(NodeList nodeList) {

    for (int count = 0; count < nodeList.getLength(); count++) {

        Node tempNode = nodeList.item(count);

        // make sure it's element node.
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

            // get node name and value
            System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
            System.out.println("Node Value =" + tempNode.getTextContent());

            if (tempNode.hasAttributes()) {

                // get attributes names and values
                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  . co m*/

            }

            if (tempNode.hasChildNodes()) {

                // loop again if has child nodes
                printNote(tempNode.getChildNodes());

            }

            System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");

        }

    }

}

From source file:com.wavemaker.tools.pws.install.PwsInstall.java

public static Document insertImport(Document doc, String resource) {
    List<Node> targetList = new ArrayList<Node>();

    // First, delete old lines if any.

    NodeList list = doc.getElementsByTagName("import");
    Node node = null;
    for (int i = 0; i < list.getLength(); i++) {
        node = list.item(i);/*from   w  w w  .jav  a2  s .c  o  m*/
        NamedNodeMap attributes = node.getAttributes();
        for (int j = 0; j < attributes.getLength(); j++) {
            Node attr = attributes.item(j);
            if (attr.getNodeName().equals("resource") && attr.getNodeValue().equals(resource)) {
                targetList.add(node);
                break;
            }
        }
    }

    NodeList beans_list = doc.getElementsByTagName("beans");
    Node beans_node = beans_list.item(0);

    if (targetList.size() > 0) {
        for (Node target : targetList) {
            beans_node.removeChild(target);
        }
    }

    // Now, add the new line

    NodeList list1 = beans_node.getChildNodes();
    Node bean_node = null;
    for (int i = 0; i < list1.getLength(); i++) {
        Node node1 = list1.item(i);
        if (node1.getNodeName().equals("bean")) {
            bean_node = node1;
            break;
        }
    }

    Element elem = doc.createElement("import");
    elem.setAttribute("resource", resource);

    try {
        if (bean_node != null) {
            beans_node.insertBefore(elem, bean_node);
        } else {
            beans_node.appendChild(elem);
        }
    } catch (DOMException ex) {
        ex.printStackTrace();
    }

    return doc;
}

From source file:com.vmware.o11n.plugin.powershell.model.RemotePsType.java

/**
 * Returns child element containing attribute 'N' maching provided name. 
 * @param node Child nodes to be searched
 * @param name Search name//  w  w  w .  java2  s  . com
 * @return maching element.
 */
private static Node getChildByNameAttr(final Node node, final String name) {
    ;
    NodeList childs = node.getChildNodes();
    for (int i = 0; i < childs.getLength(); i++) {
        Node child = childs.item(i);
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            Node nodeName = child.getAttributes().getNamedItem("N");
            if (nodeName != null && nodeName.getTextContent().equals(name)) {
                return child;
            }
        }
    }

    return null;
}

From source file:org.jboss.as.test.integration.logging.formatters.XmlFormatterTestCase.java

private static void validateStackTrace(final Node element) {
    Assert.assertEquals(Node.ELEMENT_NODE, element.getNodeType());
    Assert.assertNotNull(element.getAttributes().getNamedItem("refId"));
    final NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        final Node child = children.item(i);
        final String name = child.getNodeName();
        if ("causedBy".equals(name) || "suppressed".equals(name)) {
            validateStackTrace(child.getFirstChild());
        }//from  w w w . j  av  a 2s .  c o m
    }
}

From source file:com.portfolio.data.utils.DomUtils.java

public static String getNodeAttributesString(Node node) {
    String ret = "";
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attribute = (Attr) attributes.item(i);
        ret += attribute.getName().trim() + "=\"" + StringEscapeUtils.escapeXml11(attribute.getValue().trim())
                + "\" ";
    }//from  w w  w.java2  s  .c  o m
    return ret;
}

From source file:main.flureport.FluReportSpeechlet.java

public static SpeechletResponse GetFluLevelByStateIntent(Intent intent, Session session, Slot slot) {
    if (slot.equals(null)) {
        String speechOutput = "I misunderstood you.  Please make your request again.";
        // Create the plain text output
        SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech();
        outputSpeech.setSsml("<speak>" + speechOutput + "</speak>");
        return SpeechletResponse.newTellResponse(outputSpeech);
    }//from   w ww. j a v a  2  s  .c  om
    String stateSlotString = slot.getValue().toString().toUpperCase();
    System.out.println("**********stateSlotString" + stateSlotString);
    String standardizedStateName = null;
    try {
        standardizedStateName = convertStateIntentToStateEnum(slot);
        System.out.println("***standardizedStateName***" + standardizedStateName);
    } catch (NullPointerException npe) {
        System.out.println("The stateSlotString string from the StateSlot param in "
                + "convertStateIntentToStateEnum is null. Exception: " + npe);
        String speechOutput = "I misunderstood you.  Please make your request again.";
        // Create the plain text output
        SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech();
        outputSpeech.setSsml("<speak>" + speechOutput + "</speak>");
        return SpeechletResponse.newTellResponse(outputSpeech);
    }
    try {
        doc = fluReport.getFluReport();
    } catch (NullPointerException npe) {
        System.out.println("fluReport.getFluReport(): " + npe);
    }
    String fluLevelforState = null;
    if (doc.equals(null)) {
        System.out.println("$$$$$ NULL INFLUENZA INFORMATION");
    }
    ;
    NodeList listOfTimeperiods = doc.getElementsByTagName("timeperiod");
    Node mostRecentReportNode = XMLPAXParseWebCall.getMostRecentNode(listOfTimeperiods);
    String subtitle = mostRecentReportNode.getAttributes().getNamedItem("subtitle").getNodeValue().toString();
    try {
        fluLevelforState = XMLPAXParseWebCall.getStateReport(standardizedStateName, mostRecentReportNode);
        System.out.println(
                "list of Prevalence of influenza in " + standardizedStateName + " is " + fluLevelforState);
    } catch (NullPointerException e) {
        System.out.println("in GetFluLevelByStateIntent(), fluLevelforState: " + e);
    }
    String speechPrefixContent = "<p>For the " + subtitle + "</p> ";
    String cardPrefixContent = "For the State of " + standardizedStateName
            + ", The CDC report the prevalence of the influenza as " + fluLevelforState + ".";
    String cardTitle = "Influenza Information";
    String speechOutput = "For the State of " + standardizedStateName
            + ", The CDC report the prevalence of the influenza as " + fluLevelforState + ".";
    String repromptText = "Influenza Information can give you a list of states where the CDC reports that influenza infections"
            + "are widespread. To get this report say something like, where is the influenza or in which states is the "
            + "influenza widespread.  Influenza Information can also tell you the prevelance of influenza in any state as "
            + "reported by the CDC. Ask for this by saying, give me influenza information for Florida or "
            + "what is the influenza prevalence in California."
            + "Would you like to get another state specific "
            + "report or a list of states with widespread influenza?";
    String askForNextStep = " Would you like to get a state specific "
            + "report or a list of states with widespread influenza?";

    if (StringUtils.isEmpty(fluLevelforState) || fluLevelforState == null || doc == null) {
        speechOutput = "There is no report available at this time." + " Please try again later.";
        // Create the plain text output
        SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech();
        outputSpeech.setSsml("<speak>" + speechOutput + "</speak>");
        return SpeechletResponse.newTellResponse(outputSpeech);
    } else if (fluLevelforState.equalsIgnoreCase("not found")) {
        speechOutput = "I missunderstood you.  Please make your request again.";
        // Create the plain text output
        SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech();
        outputSpeech.setSsml("<speak>" + speechOutput + "</speak>");
        return SpeechletResponse.newTellResponse(outputSpeech);
    } else {
        StringBuilder speechOutputBuilder = new StringBuilder();
        speechOutputBuilder.append(speechPrefixContent);
        speechOutputBuilder.append(speechOutput);
        speechOutputBuilder.append(askForNextStep);
        speechOutput = speechOutputBuilder.toString();

        StringBuilder cardOutputBuilder = new StringBuilder();
        cardOutputBuilder.append(cardPrefixContent);
        cardOutputBuilder.append(askForNextStep);

        // Create the Simple card content.
        SimpleCard card = new SimpleCard();
        card.setTitle(cardTitle);
        card.setContent(cardOutputBuilder.toString());
        SpeechletResponse response = newAskResponse("<speak>" + speechOutput + "</speak>", true, repromptText,
                false);
        response.setCard(card);
        return response;
    }
}

From source file:com.ryderbot.utils.ModelUtils.java

public static CorporationSheet generateCorpSheet(Node node) {
    Map<String, String> map = new HashMap<>();
    Map<Long, String> divisions = new HashMap<>();
    Map<Long, String> walletDivisions = new HashMap<>();
    Logo logo = new Logo(null);

    NodeList children = node.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);

        String key = child.getNodeName();
        if (key.equals("rowset")) {
            String name = child.getAttributes().getNamedItem("name").getNodeValue();

            NodeList rowset = child.getChildNodes();
            for (int j = 0; j < rowset.getLength(); j++) {
                try {
                    NamedNodeMap attributes = rowset.item(j).getAttributes();

                    Long accountKey = Long.parseLong(attributes.getNamedItem("accountKey").getNodeValue());
                    String description = attributes.getNamedItem("description").getNodeValue();

                    if (description.equals("Wallet Division 1")) {
                        description = "Master Wallet";
                    }//from   ww  w  . j  a  v  a 2s . co m

                    if (name.equals("divisions")) {
                        divisions.put(accountKey, description);
                    } else if (name.equals("walletDivisions")) {
                        walletDivisions.put(accountKey, description);
                    }
                } catch (Exception e) {
                    continue;
                }
            }
        } else if (key.equals("logo")) {
            //            Node current = child.getFirstChild();
            //            Long graphicID = Long.parseLong(current.getTextContent());
            //            logo = new Logo(graphicID);
            //            
            //            current = current.getNextSibling();
            //            Integer value = Integer.parseInt(current.getTextContent());
            //            logo.setShape1(value);
            //            
            //            current = current.getNextSibling();
            //            value = Integer.parseInt(current.getTextContent());
            //            logo.setShape2(value);
            //            
            //            current = current.getNextSibling();
            //            value = Integer.parseInt(current.getTextContent());
            //            logo.setShape3(value);
            //            
            //            current = current.getNextSibling();
            //            value = Integer.parseInt(current.getTextContent());
            //            logo.setColor1(value);
            //            
            //            current = current.getNextSibling();
            //            value = Integer.parseInt(current.getTextContent());
            //            logo.setColor2(value);
            //            
            //            current = current.getNextSibling();
            //            value = Integer.parseInt(current.getTextContent());
            //            logo.setColor3(value);
        } else {
            String value = child.getTextContent();

            map.put(key, value);
        }
    }

    Long corporationID = Long.parseLong(map.get("corporationID"));
    CorporationSheet corpSheet = new CorporationSheet(corporationID);

    String corporationName = map.get("corporationName");
    String ticker = map.get("ticker");
    Long ceoID = Long.parseLong(map.get("ceoID"));
    String ceoName = map.get("ceoName");
    Long stationID = Long.parseLong(map.get("stationID"));
    String stationName = map.get("stationName");
    String description = map.get("description");
    String url = map.get("url");
    Long allianceID = Long.parseLong(map.get("allianceID"));
    Long factionID = Long.parseLong(map.get("factionID"));
    String allianceName = map.get("allianceName");
    Double taxRate = Double.parseDouble(map.get("taxRate"));
    Integer memberCount = Integer.parseInt(map.get("memberCount"));
    Integer memberLimit = Integer.parseInt(map.get("memberLimit"));
    Long shares = Long.parseLong(map.get("shares"));

    corpSheet.setCorporationName(corporationName);
    corpSheet.setTicker(ticker);
    corpSheet.setCeoID(ceoID);
    corpSheet.setCeoName(ceoName);
    corpSheet.setStationID(stationID);
    corpSheet.setStationName(stationName);
    corpSheet.setDescription(description);
    corpSheet.setUrl(url);
    corpSheet.setAllianceID(allianceID);
    corpSheet.setFactionID(factionID);
    corpSheet.setAllianceName(allianceName);
    corpSheet.setTaxRate(taxRate);
    corpSheet.setMemberCount(memberCount);
    corpSheet.setMemberLimit(memberLimit);
    corpSheet.setShares(shares);
    corpSheet.setDivisions(divisions);
    corpSheet.setWalletDivisions(walletDivisions);
    corpSheet.setLogo(logo);

    return corpSheet;
}

From source file:MainClass.java

static void listNodes(Node node, String indent) {
    String nodeName = node.getNodeName();
    System.out.println(indent + " Node: " + nodeName);
    short type = node.getNodeType();
    System.out.println(indent + " Node Type: " + nodeType(type));
    if (type == TEXT_NODE) {
        System.out.println(indent + " Content is: " + ((Text) node).getWholeText());
    } else if (node.hasAttributes()) {
        System.out.println(indent + " Element Attributes are:");
        NamedNodeMap attrs = node.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Attr attribute = (Attr) attrs.item(i);
            System.out.println(indent + " " + attribute.getName() + " = " + attribute.getValue());
        }/*from w ww  .j av  a  2s  .  c o  m*/
    }

    NodeList list = node.getChildNodes();
    if (list.getLength() > 0) {
        System.out.println(indent + " Child Nodes of " + nodeName + " are:");
        for (int i = 0; i < list.getLength(); i++) {
            listNodes(list.item(i), indent + "  ");
        }
    }
}