Parsing an XML string with Xerces using InputSource --I get a null pointer
843834Oct 18 2007 — edited Oct 18 2007I am new to the Xerces parser and I am not sure I am doing this correctly. I was able to completely parse a xml file however when I tried to parse a string.... things got a little wierd. Currently I am able to parse Valid in this example code I have but I cannot parse VCID. If you notice in my string
Valid is set up in my string like this <Valid>78787</Valid> (this works!)
VCID is set up in my string like this <VCID />77888 (this comes up null yet it is good XML form)
What am I doing Wrong?
Here is my code:
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class StringToDom {
private static final String ADOC = "<CustomerInfo><Valid>78787</Valid><VCID/>77888</CustomerInfo>";
public static void main( String[] args ) {
try {
String textVal = null;
String textValid = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( ADOC ) );
Document d = builder.parse( is );
System.out.println( "the document: " + d );
Element docEle = d.getDocumentElement();
NodeList n2 = docEle.getElementsByTagName("Valid");
NodeList n3 = docEle.getElementsByTagName("VCID");
Element e2 = (Element)n2.item(0);
Element e3 = (Element)n3.item(0);
textVal = e2.getFirstChild().getNodeValue();
textValid = e3.getFirstChild().getNodeValue();
System.out.println("textVal: "+textVal);
System.out.println(" textValid: "+textValid);
}
catch( Exception ex ) {
ex.printStackTrace();
}
}
}
Cheers!
Eric Hickam
Edited by: Eric_Hickam on Oct 18, 2007 6:59 AM
Edited by: Eric_Hickam on Oct 18, 2007 7:00 AM
Edited by: Eric_Hickam on Oct 18, 2007 7:01 AM