I want to read two different XML files and compare text values of some tags. Here is my code
Both the XMLs have following structure:
<root>
<message id="1">
<text-to-compare>Some text </text-to-compare>
</message>
<message id="2">
<text-to-compare>Some text </text-to-compare>
</message>
</root>
package com.buzz.test;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class GenerateOutputFile {
private final static String LASTRUN_FILE = "resources/lastRun.xml";
private final static String PREVRUN_FILE = "resources/prevRun.xml";
public void generateAndCompare() {
compareOutput();
}
private void compareOutput() {
NodeList lastRunNodes = parseXmlFileAndGetNodes(LASTRUN_FILE);
NodeList prevRunNodes = parseXmlFileAndGetNodes(PREVRUN_FILE);
if (lastRunNodes != null && lastRunNodes.getLength() > 0
&& prevRunNodes != null
&& lastRunNodes.getLength() == prevRunNodes.getLength()) {
for (int i = 0; i < lastRunNodes.getLength(); i++) {
Element lastRunEle = (Element) lastRunNodes.item(i);
Element prevRunEle = (Element) prevRunNodes.item(i);
String lastChunk = getTextValue(lastRunEle, "text-to-compare");
String prevChunk = getTextValue(prevRunEle, "text-to-compare");
if (lastChunk != prevChunk) {
System.out.println(lastRunEle.getAttribute("id")); }
}
}
}
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
private NodeList parseXmlFileAndGetNodes(String fileName) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom = null;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(fileName);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return parseDocument(dom);
}
private NodeList parseDocument(Document dom) {
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("message");
return nl;
}
}
My problem is even when the text values of both the XML tags are same, it still prints out the id value. Any idea what could be the reason for this? Kindly help!
Thanks in advance!