Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:Main.java

/**
 * Format generated xml doc by indentation
 *
 * @param node   For java, rather than GWT
 * @param indent//w ww.  j ava  2s  . 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

private static void traverseNode(Node parentNode, JsonObject parentJson, JsonObject upperJson) {
    NodeList childList = parentNode.getChildNodes();
    for (int i = 0; i < childList.getLength(); i++) {
        JsonObject childJson = new JsonObject();
        Node childNode = childList.item(i);

        if (childNode.getNodeType() == Node.TEXT_NODE) {
            if (childNode.getNodeValue().trim().length() != 0) {
                // non empty text node reached, so add to the parent
                processTextNode(parentNode, upperJson, childJson, childNode);
            }/* www .jav a2s  . com*/
        } else if (childNode.getNodeType() == Node.ELEMENT_NODE) {

            if (childNode.hasAttributes()) {
                // attributes exist, so go thru them
                traverseAttributes(childJson, childNode);
            }

            if (childNode.hasChildNodes()) {
                // child nodes exist, so go into them
                traverseNode(childNode, childJson, parentJson);
            }

            if (childNode.getNodeType() != Node.TEXT_NODE) {
                // non text node element
                if (ADDED_BY_VALUE.contains(childNode)) {
                    // already added as a value
                    if (parentJson.has(childNode.getNodeName())) {
                        // there is already such an element as expected
                        JsonElement existing = parentJson.get(childNode.getNodeName());
                        if (existing instanceof JsonPrimitive) {
                            // it is a primitive as expected
                            Iterator attrs = childJson.entrySet().iterator();
                            if (attrs.hasNext()) {
                                // there are attributes, so reorganize the element to include the attributes and the
                                // value as property - #text
                                reorganizeForAttributes(parentJson, childNode, existing, attrs);
                            }
                        } else if (existing instanceof JsonArray) {
                            // already added and reorganized as an array, so take the last element of this type and
                            // add the attributes
                            Iterator attrs = childJson.entrySet().iterator();
                            if (attrs.hasNext()) {
                                reorganizeAddAttributes(childNode, attrs);
                            }
                        } else if (existing instanceof JsonObject) {
                            System.err.println("ERROR: found object, but expected primitive or array");
                        }
                    } else {
                        System.err.println("ERROR: expected element, but it does not exist");
                    }
                    // remove it from the list
                    ADDED_BY_VALUE.remove(childNode);
                } else {
                    if (parentJson.has(childNode.getNodeName())) {
                        // parent already has such an element
                        JsonElement existing = parentJson.get(childNode.getNodeName());
                        if (existing instanceof JsonArray) {
                            // and it is already an array, so just add the child to the array
                            ((JsonArray) existing).add(childJson);
                        } else if (existing instanceof JsonObject) {
                            // and it not an array, so reorganize the element
                            reorganizeElement(parentNode, parentJson, childJson, childNode, existing);
                        }
                    } else {
                        // no such an element yet, so add it to the parent
                        parentJson.add(childNode.getNodeName(), childJson);
                    }
                }
            }
        } else if (childNode.getNodeType() == Node.CDATA_SECTION_NODE) {
            // processTextNode(parentNode, upperJson, childJson, childNode);
            String base64 = Base64.getEncoder().encodeToString(childNode.getNodeValue().getBytes());
            parentJson.addProperty(childNode.getNodeName(), base64);
        } else {
            System.err.println("ERROR: unsupported node type: " + childNode.getNodeType());
        }
    }
}

From source file:DocWriter.java

private static void writeNode(Node node, Writer out, String indent) throws IOException {
    out.write(nodeWithAttrs(node, indent));
    NodeList kids = node.getChildNodes();
    if (kids != null) {
        if ((kids.item(0) != null) && (kids.item(0).getNodeType() == Node.ELEMENT_NODE)) {
            out.write('\n');
        }//w  w w.  ja va  2  s.co m
        for (int i = 0; i < kids.getLength(); i++) {
            serializeNode(kids.item(i), out, indent + SINGLE_INDENT);
        }
        /* RLR - bug in indent logic - seems to work OK without
           if ( ( kids.item( 0 ) != null ) &&
         ( kids.item( kids.getLength()-1).getNodeType() == Node.ELEMENT_NODE ) )
           {
        out.write( indent );
           }
           */
    }
    if (node.hasChildNodes()) {
        /* indent bug - leave out
        if ( kids.item( 0 ) != null && kids.item( 0 ).getNodeType() == Node.ELEMENT_NODE )
        {
           out.write( indent );
        }
        */
        out.write("</" + node.getNodeName() + ">");
    }
}

From source file:Main.java

public static String getpathToRoot(Node n) {
    // log.severe("getpathToRoot called");
    String path = "";
    Node Parent = null;/* ww  w. j  a v a2s  .c  o m*/
    int y = 0;
    if (n != null) {

        while (n.getParentNode() != null) {

            Parent = n.getParentNode();
            if (y > 0) {
                path = ":" + path;
            }
            y++;
            int i = getCurrentPosition(n);
            i = i - 1;
            // log.finest("Current position of Node = " + i);
            // Element elem = (Element) n;
            // log.finest("Node = " + elem.getLocalName() +
            // " AttribName = "+
            // elem.getAttribute("name"));
            // Check to see it has children as otherwise the htmltree has a
            // problem with expanding leaves.
            if (n.hasChildNodes()) {
                path = i + path;
            }
            n = Parent;

        }
    }

    // log.severe("path = " + path);
    if (path == null || path.length() == 0) {
        path = "0";

    }

    return path;
}

From source file:isl.FIMS.utils.Utils.java

public static Node removeNode(Node root, String elementName, boolean deep) {
    if (!(root.hasChildNodes())) {
        return null;
    }// w  w  w.  j av a  2 s . co  m

    Node matchingNode = null;
    String nodeName = null;
    Node child = null;

    NodeList childNodes = root.getChildNodes();
    int noChildren = childNodes.getLength();
    for (int i = 0; i < noChildren; i++) {
        if (matchingNode == null) {
            child = childNodes.item(i);
            nodeName = child.getNodeName();
            if ((nodeName != null) & (nodeName.equals(elementName))) {
                root.removeChild(child);
                return child;
            }
            if (deep) {
                matchingNode = removeNode(child, elementName, deep);
            }
        } else {
            break;
        }
    }

    return matchingNode;
}

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());

                }//from  w w  w . j a v  a 2s.c  o 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.rapidminer.gui.OperatorDocLoader.java

/**
 * /*from  w w  w. ja  va2  s.com*/
 * @param operatorWikiName
 * @param opDesc
 * @return The parsed <tt>Document</tt> (not finally parsed) of the selected operator.
 * @throws MalformedURLException
 * @throws ParserConfigurationException
 */
private static Document parseDocumentForOperator(String operatorWikiName, OperatorDescription opDesc)
        throws MalformedURLException, ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setIgnoringComments(true);
    builderFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new XHTMLEntityResolver());

    Document document = null;
    URL url = new URL(WIKI_PREFIX_FOR_OPERATORS + operatorWikiName);
    if (url != null) {
        try {
            document = documentBuilder.parse(WebServiceTools.openStreamFromURL(url));
        } catch (IOException e) {
            logger.warning("Could not open " + url.toExternalForm() + ": " + e.getMessage());
        } catch (SAXException e) {
            logger.warning("Could not parse operator documentation: " + e.getMessage());
        }

        int i = 0;

        if (document != null) {
            Element contentElement = document.getElementById("content");

            // removing content element from document
            if (contentElement != null) {
                contentElement.getParentNode().removeChild(contentElement);
            }

            // removing everything from body
            NodeList bodies = document.getElementsByTagName("body");
            for (int k = 0; k < bodies.getLength(); k++) {
                Node body = bodies.item(k);
                while (body.hasChildNodes()) {
                    body.removeChild(body.getFirstChild());
                }

                // read content element to body
                if (contentElement != null && k == 0) {
                    body.appendChild(contentElement);
                }
            }

            // removing everything from head
            NodeList heads = document.getElementsByTagName("head");
            for (int k = 0; k < heads.getLength(); k++) {
                Node head = heads.item(k);
                while (head.hasChildNodes()) {
                    head.removeChild(head.getFirstChild());
                }
            }
            // removing...<head/> from document
            if (heads != null) {
                while (i < heads.getLength()) {
                    Node head = heads.item(i);
                    head.getParentNode().removeChild(head);
                }
            }

            // removing jump-to-nav element from document
            Element jumpToNavElement = document.getElementById("jump-to-nav");
            if (jumpToNavElement != null) {
                jumpToNavElement.getParentNode().removeChild(jumpToNavElement);
            }

            // removing mw-normal-catlinks element from document
            Element mwNormalCatlinksElement = document.getElementById("mw-normal-catlinks");
            if (mwNormalCatlinksElement != null) {
                mwNormalCatlinksElement.getParentNode().removeChild(mwNormalCatlinksElement);
            }

            // removing complete link navigation
            Element tocElement = document.getElementById("toc");
            if (tocElement != null) {
                tocElement.getParentNode().removeChild(tocElement);
            }

            // removing everything from class printfooter
            NodeList nodeListDiv = document.getElementsByTagName("div");
            for (int k = 0; k < nodeListDiv.getLength(); k++) {
                Element div = (Element) nodeListDiv.item(k);
                if (div.getAttribute("class").equals("printfooter")) {
                    div.getParentNode().removeChild(div);
                }
            }

            // removing everything from class editsection
            NodeList spanList = document.getElementsByTagName("span");
            for (int k = 0; k < spanList.getLength(); k++) {
                Element span = (Element) spanList.item(k);
                if (span.getAttribute("class").equals("editsection")) {
                    span.getParentNode().removeChild(span);
                }
            }

            // Synopsis Header
            boolean doIt = true;
            NodeList pList = document.getElementsByTagName("p");
            for (int k = 0; k < pList.getLength(); k++) {

                if (doIt) {
                    Node p = pList.item(k);
                    NodeList pChildList = p.getChildNodes();

                    for (int j = 0; j < pChildList.getLength(); j++) {

                        Node pChild = pChildList.item(j);
                        if (pChild.getNodeType() == Node.TEXT_NODE && pChild.getNodeValue() != null
                                && StringUtils.isNotBlank(pChild.getNodeValue())
                                && StringUtils.isNotEmpty(pChild.getNodeValue())) {

                            String pChildString = pChild.getNodeValue();
                            Element newPWithoutSpaces = document.createElement("p");
                            newPWithoutSpaces.setTextContent(pChildString);

                            Node synopsis = document.createTextNode("Synopsis");

                            Element span = document.createElement("span");
                            span.setAttribute("class", "mw-headline");
                            span.setAttribute("id", "Synopsis");
                            span.appendChild(synopsis);

                            Element h2 = document.createElement("h2");
                            h2.appendChild(span);

                            Element div = document.createElement("div");
                            div.setAttribute("id", "synopsis");
                            div.appendChild(h2);
                            div.appendChild(newPWithoutSpaces);

                            Node pChildParentParent = pChild.getParentNode().getParentNode();
                            Node pChildParent = pChild.getParentNode();

                            pChildParentParent.replaceChild(div, pChildParent);
                            doIt = false;
                            break;
                        }
                    }
                } else {
                    break;
                }
            }

            // removing all <br...>-Tags
            NodeList brList = document.getElementsByTagName("br");

            while (i < brList.getLength()) {
                Node br = brList.item(i);
                Node parentBrNode = br.getParentNode();
                parentBrNode.removeChild(br);
            }

            // removing everything from script
            NodeList scriptList = document.getElementsByTagName("script");
            while (i < scriptList.getLength()) {
                Node scriptNode = scriptList.item(i);
                Node parentNode = scriptNode.getParentNode();
                parentNode.removeChild(scriptNode);
            }

            // removing all empty <p...>-Tags
            NodeList pList2 = document.getElementsByTagName("p");
            int ccc = 0;
            while (ccc < pList2.getLength()) {
                Node p = pList2.item(ccc);
                NodeList pChilds = p.getChildNodes();

                int kk = 0;

                while (kk < pChilds.getLength()) {
                    Node pChild = pChilds.item(kk);
                    if (pChild.getNodeType() == Node.TEXT_NODE) {
                        String pNodeValue = pChild.getNodeValue();
                        if (pNodeValue == null || StringUtils.isBlank(pNodeValue)
                                || StringUtils.isEmpty(pNodeValue)) {
                            kk++;
                        } else {
                            ccc++;
                            break;
                        }
                    } else {
                        ccc++;
                        break;
                    }
                    if (kk == pChilds.getLength()) {
                        Node parentBrNode = p.getParentNode();
                        parentBrNode.removeChild(p);
                    }
                }
            }

            // removing firstHeading element from document
            Element firstHeadingElement = document.getElementById("firstHeading");
            if (firstHeadingElement != null) {
                CURRENT_OPERATOR_NAME_READ_FROM_RAPIDWIKI = firstHeadingElement.getFirstChild().getNodeValue()
                        .replaceFirst(".*:", "");
                firstHeadingElement.getParentNode().removeChild(firstHeadingElement);
            }

            // setting operator plugin name
            if (opDesc != null && opDesc.getProvider() != null) {
                CURRENT_OPERATOR_PLUGIN_NAME = opDesc.getProvider().getName();
            }

            // removing sitesub element from document
            Element siteSubElement = document.getElementById("siteSub");
            if (siteSubElement != null) {
                siteSubElement.getParentNode().removeChild(siteSubElement);
            }

            // removing contentSub element from document
            Element contentSubElement = document.getElementById("contentSub");
            if (contentSubElement != null) {
                contentSubElement.getParentNode().removeChild(contentSubElement);
            }

            // removing catlinks element from document
            Element catlinksElement = document.getElementById("catlinks");
            if (catlinksElement != null) {
                catlinksElement.getParentNode().removeChild(catlinksElement);
            }

            // removing <a...> element from document, if they are empty
            NodeList aList = document.getElementsByTagName("a");
            if (aList != null) {
                int k = 0;
                while (k < aList.getLength()) {
                    Node a = aList.item(k);
                    Element aElement = (Element) a;
                    if (aElement.getAttribute("class").equals("internal")) {
                        a.getParentNode().removeChild(a);
                    } else {
                        Node aChild = a.getFirstChild();
                        if (aChild != null
                                && (aChild.getNodeValue() != null && aChild.getNodeType() == Node.TEXT_NODE
                                        && StringUtils.isNotBlank(aChild.getNodeValue())
                                        && StringUtils.isNotEmpty(aChild.getNodeValue())
                                        || aChild.getNodeName() != null)) {
                            Element aChildElement = null;
                            if (aChild.getNodeName().startsWith("img")) {
                                aChildElement = (Element) aChild;

                                Element imgElement = document.createElement("img");
                                imgElement.setAttribute("alt", aChildElement.getAttribute("alt"));
                                imgElement.setAttribute("class", aChildElement.getAttribute("class"));
                                imgElement.setAttribute("height", aChildElement.getAttribute("height"));
                                imgElement.setAttribute("src",
                                        WIKI_PREFIX_FOR_IMAGES + aChildElement.getAttribute("src"));
                                imgElement.setAttribute("width", aChildElement.getAttribute("width"));
                                imgElement.setAttribute("border", "1");

                                Node aParent = a.getParentNode();
                                aParent.replaceChild(imgElement, a);
                            } else {
                                k++;
                            }
                        } else {
                            a.getParentNode().removeChild(a);
                        }
                    }
                }
            }

        }
    }
    return document;
}

From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtilsV4.java

public static void writeSubtree(final ODataClient client, final JsonGenerator jgen, final Node content,
        final boolean propType) throws IOException {
    for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
        final String childName = XMLUtils.getSimpleName(child);

        final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) {
            jgen.writeStringField(/*  w  w w  .j  av a2  s  .  c om*/
                    propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
                    typeAttr.getTextContent());

            jgen.writeObjectFieldStart(childName);
            GeospatialJSONHandler.serialize(jgen, (Element) child, typeAttr.getTextContent());
            jgen.writeEndObject();
        } else if (XMLUtils.hasOnlyTextChildNodes(child)) {
            if (child.hasChildNodes()) {
                final String out;
                if (typeAttr == null) {
                    out = child.getChildNodes().item(0).getNodeValue();
                } else {
                    if (typeAttr.getTextContent().startsWith("Edm.")) {
                        final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent());
                        final ODataPrimitiveValue value = client.getPrimitiveValueBuilder().setType(type)
                                .setText(child.getChildNodes().item(0).getNodeValue()).build();
                        out = value.toString();

                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
                    } else {
                        // enum
                        out = child.getTextContent();
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                    }
                }
                jgen.writeStringField(childName, out);
            } else {
                if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
                    if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) {
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                        jgen.writeStringField(childName, StringUtils.EMPTY);
                    } else {
                        jgen.writeArrayFieldStart(childName);
                        jgen.writeEndArray();
                    }
                } else {
                    jgen.writeNullField(childName);
                }
            }
        } else {
            if (XMLUtils.hasElementsChildNode(child)) {
                jgen.writeArrayFieldStart(childName);

                for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
                    if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
                        jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
                    } else {
                        jgen.writeStartObject();
                        DOMTreeUtils.writeSubtree(client, jgen, nephew);
                        jgen.writeEndObject();
                    }
                }

                jgen.writeEndArray();
            } else {
                jgen.writeObjectFieldStart(childName);
                if (typeAttr != null) {
                    jgen.writeStringField("@" + ODataConstants.JSON_TYPE, typeAttr.getTextContent());
                }

                DOMTreeUtils.writeSubtree(client, jgen, child);

                jgen.writeEndObject();
            }
        }
    }
}

From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtilsV3.java

/**
 * Serializes DOM content as JSON./*w w  w  .  j av  a 2  s. c o  m*/
 *
 * @param client OData client.
 * @param jgen JSON generator.
 * @param content content.
 * @param propType whether to output type information in the way needed for property values or not.
 * @throws IOException in case of write error.
 */
public static void writeSubtree(final ODataClient client, final JsonGenerator jgen, final Node content,
        final boolean propType) throws IOException {

    for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
        final String childName = XMLUtils.getSimpleName(child);

        final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) {
            jgen.writeStringField(
                    propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
                    typeAttr.getTextContent());

            jgen.writeObjectFieldStart(childName);
            GeospatialJSONHandler.serialize(jgen, (Element) child, typeAttr.getTextContent());
            jgen.writeEndObject();
        } else if (XMLUtils.hasOnlyTextChildNodes(child)) {
            if (child.hasChildNodes()) {
                final String out;
                if (typeAttr == null) {
                    out = child.getChildNodes().item(0).getNodeValue();
                } else {
                    final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent());
                    final ODataPrimitiveValue value = client.getPrimitiveValueBuilder().setType(type)
                            .setText(child.getChildNodes().item(0).getNodeValue()).build();
                    out = value.toString();

                    jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
                }
                jgen.writeStringField(childName, out);
            } else {
                if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
                    if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) {
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                        jgen.writeStringField(childName, StringUtils.EMPTY);
                    } else {
                        jgen.writeArrayFieldStart(childName);
                        jgen.writeEndArray();
                    }
                } else {
                    jgen.writeNullField(childName);
                }
            }
        } else {
            if (XMLUtils.hasElementsChildNode(child)) {
                jgen.writeArrayFieldStart(childName);

                for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
                    if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
                        jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
                    } else {
                        jgen.writeStartObject();
                        DOMTreeUtils.writeSubtree(client, jgen, nephew);
                        jgen.writeEndObject();
                    }
                }

                jgen.writeEndArray();
            } else {
                jgen.writeObjectFieldStart(childName);
                if (typeAttr != null) {
                    jgen.writeStringField(ODataConstants.JSON_TYPE, typeAttr.getTextContent());
                }

                DOMTreeUtils.writeSubtree(client, jgen, child);

                jgen.writeEndObject();
            }
        }
    }
}

From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtils.java

/**
 * Serializes DOM content as JSON./*  w  w w  .j a  v  a2s  .  com*/
 *
 * @param jgen JSON generator.
 * @param content content.
 * @param propType whether to output type information in the way needed for property values or not.
 * @throws IOException in case of write error.
 */
public static void writeSubtree(final JsonGenerator jgen, final Node content, final boolean propType)
        throws IOException {

    for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
        final String childName = XMLUtils.getSimpleName(child);

        final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) {
            jgen.writeStringField(
                    propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
                    typeAttr.getTextContent());

            jgen.writeObjectFieldStart(childName);
            GeospatialJSONHandler.serialize(jgen, (Element) child, typeAttr.getTextContent());
            jgen.writeEndObject();
        } else if (XMLUtils.hasOnlyTextChildNodes(child)) {
            if (child.hasChildNodes()) {
                final String out;
                if (typeAttr == null) {
                    out = child.getChildNodes().item(0).getNodeValue();
                } else {
                    final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent());
                    final ODataPrimitiveValue value = new ODataPrimitiveValue.Builder().setType(type)
                            .setText(child.getChildNodes().item(0).getNodeValue()).build();
                    out = value.toString();

                    jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
                }
                jgen.writeStringField(childName, out);
            } else {
                if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
                    if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) {
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                        jgen.writeStringField(childName, StringUtils.EMPTY);
                    } else {
                        jgen.writeArrayFieldStart(childName);
                        jgen.writeEndArray();
                    }
                } else {
                    jgen.writeNullField(childName);
                }
            }
        } else {
            if (XMLUtils.hasElementsChildNode(child)) {
                jgen.writeArrayFieldStart(childName);

                for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
                    if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
                        jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
                    } else {
                        jgen.writeStartObject();
                        writeSubtree(jgen, nephew);
                        jgen.writeEndObject();
                    }
                }

                jgen.writeEndArray();
            } else {
                jgen.writeObjectFieldStart(childName);
                if (typeAttr != null) {
                    jgen.writeStringField(ODataConstants.JSON_TYPE, typeAttr.getTextContent());
                }

                writeSubtree(jgen, child);

                jgen.writeEndObject();
            }
        }
    }
}