Java XML Node Value getValueByElement(Node node)

Here you can find the source of getValueByElement(Node node)

Description

get Value By Element

License

Open Source License

Declaration

public static String getValueByElement(Node node) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static String REF = "rng:ref";
    public static String REF_NAME_ATTRIBUT = "name";
    public static String DEFINE = "rng:define";
    public static String DEFINE_NAME_ATTRIBUT = "name";
    public static String VALUE = "rng:value";

    public static String getValueByElement(Node node) {
        List<Node> ref_nodes = getChildRefNode(node);

        if (ref_nodes.size() == 1) {
            Node define_node = getDefineRefByName(
                    getRefName(ref_nodes.get(0)), node.getOwnerDocument());
            return getValueByElement(define_node);
        } else if (getNodeValue(node) != null) {
            return getNodeValue(node).getTextContent();
        } else {/* www  .  j a  v  a  2s.  co  m*/
            return "";
        }
    }

    public static List<Node> getChildRefNode(Node node) {
        List<Node> nodes = new ArrayList<Node>();

        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            Node n = node.getChildNodes().item(i);
            if (n.getNodeName().equals(REF)) {
                nodes.add(n);
            }
        }
        return nodes;
    }

    public static Node getDefineRefByName(String name, Document doc) {
        NodeList nodes = doc.getElementsByTagName(DEFINE);

        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            if (n.getAttributes().getNamedItem(DEFINE_NAME_ATTRIBUT)
                    .getNodeValue().equals(name)) {
                return n;
            }
        }

        return null;
    }

    public static String getRefName(Node node) {
        return node.getAttributes().getNamedItem(REF_NAME_ATTRIBUT)
                .getNodeValue();
    }

    public static Node getNodeValue(Node node) {

        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            Node n = node.getChildNodes().item(i);
            if (n.getNodeName().equals(VALUE)) {
                return n;
            }
        }

        return null;
    }
}

Related

  1. getValue(Node node, short nodeType)
  2. getValue(Node node, short nodeType)
  3. getValue(Node node, short nodeType)
  4. getValue(Node node, String Tag)
  5. getValue(Node pNode)
  6. getValueByTagName(Node n, String tag)
  7. getValueOfValueNode(Node n)
  8. getValues(Node metric)
  9. nodeToDouble(Node node)