package com.blogspot.abbablows.tests;
import java.io.File;
import java.io.FileInputStream;
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import junit.framework.TestCase;
/**
* JUnit test shows one method of comparing two xml files
*/
public class Example extends TestCase
{
protected void compareFiles(File actual,
File expected,
String elementName)
throws ParserConfigurationException, SAXException,
IOException
{
FileInputStream fileOne = null;
FileInputStream fileTwo = null;
try
{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
fileOne = new FileInputStream(actual);
Document firstDocument = builder.parse(fileOne);
firstDocument.getDocumentElement().normalize();
NodeList firstRoot =
firstDocument.getElementsByTagName(elementName);
fileTwo = new FileInputStream(expected);
Document secondDocument = builder.parse(fileTwo);
secondDocument.getDocumentElement().normalize();
NodeList secondRoot =
secondDocument.getElementsByTagName(elementName);
walkNodes(firstRoot, secondRoot);
}
finally
{
if (fileOne != null)
{
fileOne.close();
}
if (fileTwo != null)
{
fileTwo.close();
}
}
}
private void walkNodes(NodeList firstRoot,
NodeList secondRoot)
{
assertEquals(firstRoot.getLength(), secondRoot.getLength());
for (int i = 0; i < firstRoot.getLength(); i++)
{
Node itemOne = firstRoot.item(i);
String nameOne = itemOne.getNodeName();
String valueOne = itemOne.getNodeValue();
Node itemTwo = secondRoot.item(i);
String nameTwo = itemTwo.getNodeName();
String valueTwo = itemTwo.getNodeValue();
if (itemOne.hasChildNodes())
{
walkNodes(itemOne.getChildNodes(),
itemTwo.getChildNodes());
}
if (itemOne.hasAttributes())
{
doAttributes(itemOne, itemTwo);
}
assertEquals(nameOne, nameTwo);
if (valueOne != null && valueTwo != null)
{
assertEquals(valueOne.trim(), valueTwo.trim());
}
}
}
private void doAttributes(Node firstRoot, Node secondRoot)
{
NamedNodeMap mapOne = firstRoot.getAttributes();
NamedNodeMap mapTwo = secondRoot.getAttributes();
assertEquals(mapOne.getLength(), mapTwo.getLength());
for (int i = 0; i < mapOne.getLength(); i++)
{
Node itemOne = mapOne.item(i);
String nameOne = itemOne.getNodeName();
String valueOne = itemOne.getNodeValue();
Node itemTwo = mapTwo.item(i);
String nameTwo = itemTwo.getNodeName();
String valueTwo = itemTwo.getNodeValue();
assertEquals(nameOne, nameTwo);
if (valueOne != null && valueTwo != null)
{
assertEquals(valueOne.trim(), valueTwo.trim());
}
}
}
}
No comments:
Post a Comment