So I've been trying to collect all of the nodes Names along with their contents in pre-order. So I used a recursive method to get all of the Nodes from the XML file along with the Text. Problem is whenever I execute it I keep on getting empty strings in the ArrayList. The empty Strings are next to Academy, Faculty and Department since they got no text.
I've tried deleting empty strings and null from the ArrayList but didnt work does anyone know a way to solve this problem and thanks!
Here is the XML File:
<?xml version="1.0"?>
<Academy>
<Faculty>
<Department name= "Science">
<Director>Kay Jordan</Director>
<Don>ABC</Don>
</Department>
</Faculty>
</Academy>
And here is the Java Code:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Gen2 {
static ArrayList<String> SLDP = new ArrayList<String>(0);
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("Test.xml"));
doSomething(document.getDocumentElement());
System.out.print("< ");
SLDP.removeAll(Arrays.asList(null," "));
for(int z =0; z<SLDP.size();z++){
System.out.print(SLDP.get(z).toString()+ " ");
}
System.out.print(" >");
}
public static void doSomething(Node node) {
// do something with the current node instead of System.out
//System.out.println(node.getNodeName());
SLDP.add(node.getNodeName());
System.out.println(node.getFirstChild().getTextContent());
SLDP.add(node.getFirstChild().getTextContent());
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//calls this method for all the children which is Element
doSomething(currentNode);
}
}
}
}