Java XML NodeList to Element List toElements(NodeList nodes)

Here you can find the source of toElements(NodeList nodes)

Description

format XML into human readable form

License

Apache License

Parameter

Parameter Description
document a parameter
root a parameter
tab private static void formatXML(Document document, Element root, String tab) { NodeList children = root.getChildNodes(); // save the nodes in the array first Node[] nodes = new Node[children.getLength()]; for (int i = 0; i < children.getLength(); i++) nodes[i] = children.item(i); // insert identations for (int i = 0; i < nodes.length; i++) { root.insertBefore(document.createTextNode("\n" + tab), nodes[i]); if (nodes[i] instanceof Element) formatXML(document, (Element) nodes[i], " " + tab); } root.appendChild(document.createTextNode("\n" + tab.substring(0, tab.length() - 2))); }

Declaration


public static List<Element> toElements(NodeList nodes) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    /**/*  w w  w. j av a2  s. c o m*/
     * format XML into human readable form
     * @param document
     * @param root
     * @param tab
     *
    private static void formatXML(Document document, Element root, String tab) {
       NodeList children = root.getChildNodes();
       // save the nodes in the array first
       Node[] nodes = new Node[children.getLength()];
       for (int i = 0; i < children.getLength(); i++)
     nodes[i] = children.item(i);
       // insert identations
       for (int i = 0; i < nodes.length; i++) {
     root.insertBefore(document.createTextNode("\n" + tab), nodes[i]);
     if (nodes[i] instanceof Element)
    formatXML(document, (Element) nodes[i], "  " + tab);
       }
       root.appendChild(document.createTextNode("\n"
    + tab.substring(0, tab.length() - 2)));
    }
    */

    public static List<Element> toElements(NodeList nodes) {
        List<Element> list = new ArrayList<Element>();
        for (int i = 0; i < nodes.getLength(); i++)
            if (nodes.item(i) instanceof Element)
                list.add((Element) nodes.item(i));
        return list;
    }
}

Related

  1. toElementList(NodeList list)
  2. toElementList(NodeList nds)
  3. toElementList(NodeList nodeList)
  4. toElementList(NodeList nodeList)
  5. toElements(NodeList nl)
  6. toElements(NodeList nodes, String filter)