G'day guys,
I have written an e-commerce application where information is collected from forms and is sent over the network to a server. The server processes the request and replies back in xml, following is the failure reply:
<?xml version="1.0" encoding="UTF-8"?>
<orderConfirmation>
<error>
<message>There was an error in receiving your order.</message>
</error>
</orderConfirmation>
[\code]
I have to parse this and display success or error message.
I have written the code, but the server is giving me the following error:
javax.servlet.ServletException: The root element is required in a well-formed document.
I know this means that I have no rootElement, but I think I do have a rootElement. Anyway, I would be gratefull if u could look at my code and tell me where my problem lies.
Here is the code:
<%!
private String parseXML (String in) throws Exception{
InputSource inputSource = new InputSource ( new java.io.StringReader(in));
// Create an instance of the DOM parser and parse the document
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputSource);
// Begin traversing the document
result2 = (traverseTree(doc));
return result2;
}
%>
<%!
private String traverseTree(Node currnode) throws Exception {
// Find the type of the current node
int type = currnode.getNodeType();
// Check the node type, and process it accordingly
switch (type) {
case Node.DOCUMENT_NODE:
{
traverseTree (((Document)currnode).getDocumentElement());
break;
}
case Node.ELEMENT_NODE:
{
String elementName = currnode.getNodeName();
if (elementName.equals("error")){
status = "Unfortunately, there was an error in processing your request";
}
else{
status = "Success, your order was succesfully recieved";
}
}
}
return status;
}
%>
Since the error message is pretty simple, I thought there is no point in having a complicated parsing code. So all I want to do is get the rootElement which is always <orderConfirmation></orderConfirmation>, and I want to parse the second element. Depending on weahter this is error or success i can display appropriate information.
What am I doing wrong?
Thanks for your help people.