-
XML parsing using DOM
Hello,
I'm need to extract the contents of, say, the <Date><\Date> tags.
I'm using this sample code, but when the program runs nothing happens, there's no actual output.
Code:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class XMLParse
{
public void test()
{
try
{
DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docbuilder.parse(new File("C:\\Java\\TestFile.xml"));
Element qu = doc.getElementById("Date");
doc.getDocumentElement().normalize();
System.out.println(qu.getTextContent());
}
catch(Exception e)
{}
}
}
Can you please suggest what could be wrong?
Thanks for your help!
-
Quote:
Code:
catch(Exception e)
{}
ouch!
You sure you want to do this?
-
Hi Fubarable,
Yes I know about that, I would elaborate further on the code in regards to exceptions, this is just a test program to check about parsing.
Thanks.
-
The reason Fubarable mentioned your Exception is that there is a possibility that an exception is being caught and you are not seeing anything because of it. Basic try catch procedure suggests you at least have some type of console output inside the structure of catch(Exception e){}
Remove:
Code:
catch(Exception e){}
ADD:
Code:
catch(Exception e){e.printStackTrace();}
This will better aid you in future problems and could have helped you avoid this situation altogether. There may be a null pointer exception.
Now, in regards to your problem.
Best practice it to use xpath when you are extracting elements from an XML. Inherent nature of a DOM tree is unintuitive and can give rise to strange problems where you grab empty text nodes if your XML has strange formatting.
If you do not like xpath:
Then you are in for a wold of pain imho :D try qu.getNodeValue() or qu.getNodeName() to make sure that you are actually getting the <Date> element. I will run your code and see what I get.
-
try this. its a little dirty but it may be a step in the right direction
Code:
try{
DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docbuilder.parse(new File("C:\\Java\\TestFile.xml"));
NodeList qu = (NodeList) root.getElementsByTagName("standard_data_type");
for(int x=0; x<qu.getLength(); x++){
System.out.println(qu.item(x).getNodeName());
qu.item(x).normalize();
System.out.println(qu.item(x).getTextContent());
}
}catch(Exception e)
{e.printStackTrace();}