Example usage for org.w3c.dom Node getNodeValue

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

Introduction

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

Prototype

public String getNodeValue() throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:Utils.java

/**
 * Starting from a node, find the namespace declaration for a prefix. for a matching namespace
 * declaration.//w ww  .  ja v  a2 s .  co m
 * 
 * @param node search up from here to search for namespace definitions
 * @param searchPrefix the prefix we are searching for
 * @return the namespace if found.
 */
public static String getNamespace(Node node, String searchPrefix) {

    Element el;
    while (!(node instanceof Element)) {
        node = node.getParentNode();
    }
    el = (Element) node;

    NamedNodeMap atts = el.getAttributes();
    for (int i = 0; i < atts.getLength(); i++) {
        Node currentAttribute = atts.item(i);
        String currentLocalName = currentAttribute.getLocalName();
        String currentPrefix = currentAttribute.getPrefix();
        if (searchPrefix.equals(currentLocalName) && XMLNAMESPACE.equals(currentPrefix)) {
            return currentAttribute.getNodeValue();
        } else if (isEmpty(searchPrefix) && XMLNAMESPACE.equals(currentLocalName) && isEmpty(currentPrefix)) {
            return currentAttribute.getNodeValue();
        }
    }

    Node parent = el.getParentNode();
    if (parent instanceof Element) {
        return getNamespace((Element) parent, searchPrefix);
    }

    return null;
}

From source file:Main.java

/**
 * Serializes the given XML tree to string form, including the standard
 * XML header and indentation if desired. This method relies on the
 * serialization API from Apache Xerces, since JAXP has on equivalent.
 * //w w w  .j a  va 2  s  . co  m
 * @param xml
 *            The XML tree to serialize.
 * @param printHeader
 *            True if you want the XML header printed before the XML.
 * @param printIndents
 *            True if you want pretty-printing - child elements will be
 *            indented with symmetry.
 * @return The string representation of the given Node.
 */
public static String toString(final Node xml, final boolean printHeader, final boolean printIndents) {
    final short type = xml.getNodeType();

    if (type == Node.TEXT_NODE)
        return xml.getNodeValue();

    //
    // NOTE: This serialization code is not part of JAXP/DOM - it is 
    //       specific to Xerces and creates a Xerces dependency for 
    //       this class.
    //
    final XMLSerializer serializer = new XMLSerializer();
    serializer.setNamespaces(true);

    final OutputFormat formatter = new OutputFormat();
    formatter.setOmitXMLDeclaration(!printHeader);
    formatter.setIndenting(printIndents);
    serializer.setOutputFormat(formatter);

    final StringWriter writer = new StringWriter();
    serializer.setOutputCharStream(writer);

    try {
        if (type == Node.DOCUMENT_NODE)
            serializer.serialize((Document) xml);
        else
            serializer.serialize((Element) xml);
    }

    //
    // we are using a StringWriter, so this "should never happen". the 
    // StringWriter implementation writes to a StringBuffer, so there's 
    // no file I/O that could fail.
    //
    // if it DOES fail, we re-throw with a more serious error, because 
    // this a very common operation.
    //
    catch (final IOException error) {
        throw new RuntimeException(error.getMessage(), error);
    }

    return writer.toString();
}

From source file:Main.java

public static String getTextChild(Element element) {
    NodeList children = element.getChildNodes();
    String value = null;//from www  .  java  2s  .c o  m
    for (int i = 0; i < children.getLength(); ++i) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.TEXT_NODE) {
            if (null != value) {
                throw new IllegalStateException(
                        "Element " + elementToString(element) + " has more than one text child.");
            } else {
                value = child.getNodeValue();
            }
        }
    }
    return value;
}

From source file:Main.java

public static <T> T loadBean(Node node, Class<T> beanClass)
        throws IntrospectionException, InstantiationException, IllegalAccessException, IllegalArgumentException,
        DOMException, InvocationTargetException {
    T store = beanClass.newInstance();// ww w  .  j a v a  2 s. c o  m

    Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>();
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
        properties.put(property.getName(), property);
    }

    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        PropertyDescriptor property = properties.get(attribute.getNodeName());
        if (property != null && property.getPropertyType().equals(String.class)
                && property.getWriteMethod() != null) {
            property.getWriteMethod().invoke(store, attribute.getNodeValue());
        }
    }

    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        PropertyDescriptor property = properties.get(child.getNodeName());
        if (property != null && property.getPropertyType().equals(String.class)
                && property.getWriteMethod() != null) {
            property.getWriteMethod().invoke(store, child.getTextContent());
        }
    }

    return store;
}

From source file:com.connexta.arbitro.attr.xacml3.AttributeSelector.java

/**
 * Creates a new <code>AttributeSelector</code> based on the DOM root of the XML type. Note that
 * as of XACML 1.1 the XPathVersion element is required in any policy that uses a selector, so
 * if the <code>xpathVersion</code> string is null, then this will throw an exception.
 *
 * @param root the root of the DOM tree for the XML AttributeSelectorType XML type
 * @param metaData the meta-data associated with the containing policy
 *
 * @return an <code>AttributeSelector</code>
 *
 * @throws ParsingException if the AttributeSelectorType was invalid
 */// ww w  .j ava 2  s  .  c  o m
public static AttributeSelector getInstance(Node root, PolicyMetaData metaData) throws ParsingException {
    URI category = null;
    URI type = null;
    URI contextSelectorId = null;
    String path = null;
    boolean mustBePresent = false;
    String xpathVersion = metaData.getXPathIdentifier();

    // make sure we were given an xpath version
    if (xpathVersion == null) {
        throw new ParsingException("An XPathVersion is required for " + "any policies that use selectors");
    }

    NamedNodeMap attrs = root.getAttributes();

    try {
        // there's always a DataType attribute
        category = new URI(attrs.getNamedItem("Category").getNodeValue());
    } catch (Exception e) {
        throw new ParsingException("Error parsing required Category " + "attribute in AttributeSelector", e);
    }

    try {
        // there's always a DataType attribute
        type = new URI(attrs.getNamedItem("DataType").getNodeValue());
    } catch (Exception e) {
        throw new ParsingException("Error parsing required DataType " + "attribute in AttributeSelector", e);
    }

    try {
        // there's always a RequestPath
        path = attrs.getNamedItem("Path").getNodeValue();
    } catch (Exception e) {
        throw new ParsingException("Error parsing required " + "Path attribute in " + "AttributeSelector", e);
    }

    try {
        String stringValue = attrs.getNamedItem("MustBePresent").getNodeValue();
        mustBePresent = Boolean.parseBoolean(stringValue);
    } catch (Exception e) {
        throw new ParsingException("Error parsing required MustBePresent attribute " + "in AttributeSelector",
                e);
    }

    try {
        Node node = attrs.getNamedItem("ContextSelectorId");
        if (node != null) {
            contextSelectorId = new URI(node.getNodeValue());
        }
    } catch (Exception e) {
        throw new ParsingException("Error parsing required MustBePresent attribute " + "in AttributeSelector",
                e);
    }

    return new AttributeSelector(category, type, contextSelectorId, path, mustBePresent, xpathVersion);
}

From source file:Main.java

private static String getTextContent(Element element) {
    if (element == null) {
        return null;
    }/*from   w ww .  j  av  a2  s .  co  m*/
    Node textNode = element.getFirstChild();
    if (textNode == null) {
        return "";
    }
    if (textNode.getNodeType() != Node.TEXT_NODE) {
        throw new RuntimeException("Element " + element.getTagName() + "does not have text content");
    }
    return textNode.getNodeValue();
}

From source file:Main.java

public static int getAllChildrenString(Node start, int offset) {
    //String spacers  = "                                                         ";
    String tagOpen = "<";
    String tagClose = ">";
    String tagEndOpen = "</";
    String tagEndClose = ">";
    String tagName = start.getNodeName();
    String tagValue = (start.getNodeValue() == null ? "" : start.getNodeValue());

    if (start.getNodeName().trim().equals("#text")) {
        tagOpen = "";
        tagClose = "";
        tagName = "";
        tagEndOpen = "";
        tagEndClose = "";
    }//from w ww  .  ja va2s  .c om
    if (offset == 0)
        HTMLString = "";
    else {
        HTMLString += //spacers.substring(0, offset) +
                tagOpen + tagName;

        if (start.getNodeType() == Element.ELEMENT_NODE) {
            NamedNodeMap startAttr = start.getAttributes();
            for (int i = 0; i < startAttr.getLength(); i++) {
                Node attr = startAttr.item(i);
                HTMLString += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"";
            }
        }
        HTMLString += tagClose + tagValue;
    }

    for (Node child = start.getFirstChild(); child != null; child = child.getNextSibling()) {
        getAllChildrenString(child, offset + 1);
    }

    if (offset > 0 && tagName.length() > 0) {
        HTMLString += //spacers.substring(0, offset) +
                tagEndOpen + tagName + tagEndClose;
    }

    return ++offset;
}

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

/**
 * <p>//from w w  w  .  j  a va2 s .c o  m
 * 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:Main.java

public static int getAllChildren(Node start, int offset) {
    //String spacers  = "                                                         ";
    String tagOpen = "<";
    String tagClose = ">";
    String tagEndOpen = "</";
    String tagEndClose = ">";
    String tagName = start.getNodeName();
    String tagValue = (start.getNodeValue() == null ? "" : start.getNodeValue());

    if (start.getNodeName().trim().equals("#text")) {
        tagOpen = "";
        tagClose = "";
        tagName = "";
        tagEndOpen = "";
        tagEndClose = "";
    } else if (start.getNodeName().trim().equals("#comment")) {
        tagOpen = "<!--";
        tagClose = "";
        tagName = "";
        tagEndOpen = "";
        tagEndClose = "-->";
    }/*from ww w  .j a  va 2s.com*/
    if (offset == 0)
        HTMLString = "";

    HTMLString += tagOpen + tagName;

    if (start.getNodeType() == Element.ELEMENT_NODE) {
        NamedNodeMap startAttr = start.getAttributes();
        for (int i = 0; i < startAttr.getLength(); i++) {
            Node attr = startAttr.item(i);
            HTMLString += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"";
        }
    }
    HTMLString += tagClose + tagValue;

    for (Node child = start.getFirstChild(); child != null; child = child.getNextSibling()) {
        getAllChildren(child, offset + 1);
    }

    //if (offset > 0 && tagName.length() > 0) {
    if (tagName.length() > 0 || start.getNodeName().trim().equals("#comment")) {
        HTMLString += tagEndOpen + tagName + tagEndClose;
    }

    return ++offset;
}