Reputation: 718
I am attempting to parse an XML document and for some reason I can't get any child nodes from anything. I have tired everything I know. I originally tried using Dom4J but had major difficulties in regards to namespaces. Now I am attempting to use the standard DOM parser.
I've read through the oracle tutorial as well as others but see no advice on why my most basic of functions is failing.
I'll start by sharing my code:
package testingtemp;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class DomParser {
public static void main(String args[]){
try{
File inputFile = new File("C:\\Users\\jhamric\\Desktop\\Camt54.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root Element: "+doc.getDocumentElement().getChildNodes());
}catch (Exception e){
e.printStackTrace();
}
}
}
So simply all I want to do is return the child nodes for the root (which is "document".) There is one child node that should be returned.
<?xml version="1.0"?>
-<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.04">
-<BkToCstmrDbtCdtNtfctn>
+<GrpHdr>
-<Ntfctn>
<Id>161RD2521JI00XSZ</Id>
<CreDtTm>2016-01-27T13:25:21</CreDtTm>
This is just a very small portion of my Xml but you can clearly see thatBkToCstmrDbtCdtNtfctn should be returned as a child node in the print screen. Instead my console output looks like this:
Root Element: [Document: null]
It reports back the correct root element but then tells me there are no child nodes. What gives? Any help would be greatly appreciated!
Upvotes: 0
Views: 1969
Reputation: 32980
You are seeing the output of NodeList.toString
which is [Document: null]
. This actually does not give any meaningful information.
Use
NodeList nl = doc.getDocumentElement().getChildNodes();
System.out.println(nl.getLength());
if (nl.getLength() > 0)
System.out.println(nl.item(0).getNodeName());
to verify that your element is there.
Upvotes: 4