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:com.microsoft.tfs.core.clients.versioncontrol.workspacecache.WorkItemCheckedInfo.java

/**
 * Parse the XML doc for the persistent work items checked info.
 *
 * @param listRoot//from www  .ja  v a2  s.  co  m
 *        XML node containing the work items checked info
 * @return list of persistent work items checked info, null for empty list
 */
public static WorkItemCheckedInfo[] loadFromXML(final Element listRoot) {
    final Element[] childNodes = DOMUtils.getChildElements(listRoot);

    // Easy case for empty list.
    if (childNodes.length == 0) {
        return null;
    }

    // Allocate the result list.
    final List<WorkItemCheckedInfo> list = new ArrayList<WorkItemCheckedInfo>(childNodes.length);

    // Loop thru all children nodes which are the item themselves.
    for (final Node node : childNodes) {
        int id = 0;
        if (node.getAttributes().getNamedItem(XML_TAG_ATTRID) != null) {
            try {
                id = Integer.parseInt(node.getAttributes().getNamedItem(XML_TAG_ATTRID).getNodeValue());
            } catch (final NumberFormatException e) {
                log.warn(MessageFormat.format("Error parsing work item ID {0}, ignoring", //$NON-NLS-1$
                        node.getAttributes().getNamedItem(XML_TAG_ATTRID).getNodeValue()), e);

                // Skip this item
                continue;
            }
        }

        boolean checkedOnOff = false;
        if (node.getAttributes().getNamedItem(XML_TAG_ATTR_CHECKED) != null) {
            checkedOnOff = "1".equals(node.getAttributes().getNamedItem(XML_TAG_ATTR_CHECKED).getNodeValue()); //$NON-NLS-1$
        }

        CheckinWorkItemAction action = CheckinWorkItemAction.NONE;
        if (node.getAttributes().getNamedItem(XML_TAG_ATTR_ACTION) != null) {
            action = actionFromString(node.getAttributes().getNamedItem(XML_TAG_ATTR_ACTION).getNodeValue());
        }

        // Add item to list.
        list.add(new WorkItemCheckedInfo(id, checkedOnOff, action));
    }

    return list.toArray(new WorkItemCheckedInfo[list.size()]);
}

From source file:DocWriter.java

private static String nodeWithAttrs(Node node, String indent) {
    StringBuffer sb = new StringBuffer();
    // indent bug - leave out
    //sb.append( indent );
    sb.append("<");
    sb.append(node.getNodeName());/*  www. jav a  2  s.  co m*/

    NamedNodeMap attrs = node.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        sb.append(" ");
        Node attrNode = attrs.item(i);
        sb.append(attrNode.getNodeName());
        sb.append("=\"");
        sb.append(attrNode.getNodeValue());
        sb.append("\"");
    }

    if (!node.hasChildNodes()) {
        sb.append("/>");
    } else {
        sb.append(">");
    }

    return sb.toString();
}

From source file:Main.java

/**
 * Prints elements of the specified node.
 * // ww  w. jav  a2  s . c om
 * @param node the specified node.
 * @param level a number of indent.
 */
private static void printElement(Node node, int level) {
    for (int i = 0; i < level; i++) {
        System.out.print("  ");
    }
    System.out.print("{" + node.getNamespaceURI() + "}");
    System.out.println(node.getNodeName());
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
            printNode(attrs.item(i), level + 1);
        }
    }

    NodeList children = node.getChildNodes();
    int n = children.getLength();
    for (int i = 0; i < n; i++) {
        Node child = children.item(i);
        printNode(child, level + 1);
    }
}

From source file:Main.java

/**
 * Output a DOM node including children using a log4j logger.
 * If logger is null it will just output to system out.
 * It will indent by the number of tabs passed in.
 * This method recursively calls itself to output
 * children nodes./*from  www .  ja  v a 2 s .c om*/
 * 
 * @param logger
 * @param n
 * @param tabs
 */
public static void outputNode(Logger logger, Node n, int tabs) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < tabs; i++) {
        sb.append("\t");
    }
    sb.append("<" + n.getNodeName());

    if (n.hasAttributes()) {
        NamedNodeMap nnMap = n.getAttributes();
        for (int i = 0; i < nnMap.getLength(); i++) {
            Node att = nnMap.item(i);
            sb.append(" " + att.getNodeName() + "=\"" + att.getNodeValue() + "\"");
        }
    }
    sb.append(">");
    sb = printBuffer(logger, sb, true);

    for (int i = 0; i < tabs + 1; i++) {
        sb.append("\t");
    }
    sb.append(n.getNodeValue());
    sb = printBuffer(logger, sb, true);

    if (n.hasChildNodes()) {
        NodeList nodes = n.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            outputNode(nodes.item(i), tabs + 1);
        }
    }
    for (int i = 0; i < tabs; i++) {
        sb.append("\t");
    }
    sb.append("</" + n.getNodeName() + ">");
    sb = printBuffer(logger, sb, true);
}

From source file:net.openkoncept.vroom.VroomUtilities.java

/**
 * <p>//ww w. jav  a  2 s  .c  om
 * This method returns the attribute value of an XML node.
 * </p>
 *
 * @param node     - The XML node
 * @param attrName - Attribute name
 * @return - Value of XML attribute
 */
public static String getXmlAttributeValue(Node node, String attrName) {

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

    Node attrNode = node.getAttributes().getNamedItem(attrName);
    if (attrNode == null) {
        return null;
    }

    return attrNode.getNodeValue().trim();

}

From source file:net.roboconf.agent.internal.misc.UserDataUtils.java

private static String getSpecificAttributeOfTagInXMLFile(String filePath, String tagName, String attrName)
        throws ParserConfigurationException, SAXException, IOException {

    File fXmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName(tagName);
    Node aNode = nList.item(2);
    NamedNodeMap attributes = aNode.getAttributes();
    String attrValue = "";
    for (int a = 0; a < attributes.getLength(); a++) {
        Node theAttribute = attributes.item(a);
        if (attrName.equals(theAttribute.getNodeName()))
            attrValue = theAttribute.getTextContent().split(":")[0];
    }/*from   w w  w.  j ava  2  s  .  co  m*/

    return attrValue;
}

From source file:TryDOM.java

static void listNodes(Node node, String indent) {
        String nodeName = node.getNodeName();
        System.out.println(indent + nodeName + " Node, type is " + node.getClass().getName() + ":");
        System.out.println(node);

        if (node instanceof Element && node.hasAttributes()) {
            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());
            }//  w w w . j a v a2s. co  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 + " ");
        }
    }

From source file:com.l2jfree.gameserver.model.zone.form.Shape.java

public static Shape parseShape(Node sn, int zoneId) {
    String type = "";
    Shape shape = null;//from   w w w. j  av  a2  s . c om
    Class<?> clazz;
    Constructor<?> constructor;
    try {
        type = sn.getAttributes().getNamedItem("type").getNodeValue();
        clazz = Class.forName("com.l2jfree.gameserver.model.zone.form.Shape" + type);
        constructor = clazz.getConstructor();
        shape = (Shape) constructor.newInstance();
    } catch (Exception e) {
        _log.error("Cannot create a Shape" + type + " in zone " + zoneId);
        return null;
    }

    shape._points = new FastList<Tupel>();
    for (Node n = sn.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("point".equalsIgnoreCase(n.getNodeName())) {
            Tupel t = Tupel.parseTupel(n, zoneId);
            if (t != null)
                shape._points.add(t);
            else
                return null;
        }
    }

    if ("Cylinder".equalsIgnoreCase(type)) {
        try {
            int rad = Integer.parseInt(sn.getAttributes().getNamedItem("radius").getNodeValue());
            ((ShapeCylinder) shape).setRadius(rad);
        } catch (Exception e) {
            _log.warn("missing or wrong radius for cylinder in zone " + zoneId);
            return null;
        }
    } else if ("ExCylinder".equalsIgnoreCase(type)) {
        try {
            int innerRad = Integer.parseInt(sn.getAttributes().getNamedItem("innerRadius").getNodeValue());
            int outerRad = Integer.parseInt(sn.getAttributes().getNamedItem("outerRadius").getNodeValue());
            ((ShapeExCylinder) shape).setRadius(innerRad, outerRad);
        } catch (Exception e) {
            _log.warn("missing or wrong radius for cylinder in zone " + zoneId);
            return null;
        }
    }

    Node z1 = sn.getAttributes().getNamedItem("zMin");
    Node z2 = sn.getAttributes().getNamedItem("zMax");
    if (z1 != null && z2 != null) {
        try {
            shape._zMin = Integer.parseInt(z1.getNodeValue());
            shape._zMax = Integer.parseInt(z2.getNodeValue());
            shape._z = true;
        } catch (NumberFormatException nfe) {
            _log.error("zMin or zMax value not a number in zone " + zoneId);
            return null;
        }
    }

    Node ex = sn.getAttributes().getNamedItem("exclude");
    if (ex != null) {
        try {
            shape._exclude = Boolean.parseBoolean(ex.getNodeValue());
        } catch (Exception e) {
            _log.error("Invalid value for exclude in zone " + zoneId);
        }
    }
    Shape result = shape.prepare(zoneId);
    if (result != null) {
        result._points.clear();
        result._points = null;
    }
    return result;
}

From source file:de.fhg.iais.asc.xslt.binaries.DownloadAndScale.java

private static void copyAttributes(Node source, Element target, Iterable<String> attributeNames) {
    final NamedNodeMap sourceAttributes = source.getAttributes();

    if (sourceAttributes != null) {
        for (String attrName : attributeNames) {
            final Node inputAttr = sourceAttributes.getNamedItem(attrName);

            if (inputAttr != null) {
                target.setAttribute(attrName, inputAttr.getNodeValue());
            }// w  w  w . j a  va2 s  .co  m
        }
    }
}

From source file:Main.java

/**
 *  Returns all nodes at the bottom of path from node.
 * If element begins with '@', indicates an attribute, eg "@id"
 * The '#text' element indicates that the node has a single text child.
 * @param node    Node to apply path to//from   w w w  .  j  a va  2 s .co  m
 * @param path    Path to apply
 * @return        All Nodes at bottom of path. List may be empty, but not null.
 */
static public List<Node> extractNodes(Node node, String path) {
    if (node == null)
        return new ArrayList<Node>();
    List<Node> result = new ArrayList<Node>();
    NodeList list = node.getChildNodes();
    if (path.equals("#text"))
        result.add(node.getFirstChild());
    else if (path.charAt(0) == '@')
        result.add(node.getAttributes().getNamedItem(path.substring(1)));
    else
        for (int j = 0; j < list.getLength(); j++)
            if (list.item(j).getNodeType() == Node.ELEMENT_NODE && list.item(j).getNodeName().equals(path))
                result.add(list.item(j));
    return result;
}