Code, JavaEE

JDom XML Utility and Test

This is the beginnings of a useful JDom utility class and unit test.

 


// JDomUtil

public class JDomUtil {

public File loadXMLFile(String fullFilePath) {
 File fileToReturn = new File(fullFilePath);
 return fileToReturn;
 }

public Document createInMemoryXMLDocument(File xmlFile) {
 Document document = null;
 try {
 document = new SAXBuilder().build(xmlFile);
 } catch (JDOMException e) {
 System.out.printf("%n%s", e.toString());
 } catch (IOException e) {
 System.out.printf("%n%s", e.toString());
 }
 return document;
 }

public List<Element> navigateToDesiredXMLContent(String xpathExpr, Document document) {
 XPath xPath = null;
 List<Element> contentList = null;
 try {
 xPath = XPath.newInstance(xpathExpr);
 contentList = xPath.selectNodes(document);
 } catch (JDOMException e) {
 System.out.printf("%n%s", e.toString());
 }
 return contentList;
 }
}

// JDomUtilTest

public class JDomUtilTest {
 final String XML_PATH = "\\src\\test\\resources\\xml\\";
 final String USER_DIR = System.getProperty("user.dir");
 final String XPATH = "//TaskList/Task";
 private JDomUtil jdomUtil;

@Test
 public void testJDomUtil() {
 String xmlFilePathFormat = String.format("%s%s%s", USER_DIR, XML_PATH, "TaskList.xml");
 File xmlFile = jdomUtil.loadXMLFile(xmlFilePathFormat);
 Document document = jdomUtil.createInMemoryXMLDocument(xmlFile);
 List<Element> content = jdomUtil.navigateToDesiredXMLContent(XPATH, document);
 //System.out.printf("CONTENT: %s", content);

List<String> elementList = new LinkedList<>();
 elementList.add("id");
 elementList.add("description");
 iterateTaskXMLContent(content, elementList);
 }

private void iterateTaskXMLContent(List<Element> content, List<String> elementList) {
 if (content.size() == 0 || content.isEmpty()) {
 o("No content found in content list.");
 }
 for (Element element : content) {
 for (String elementName : elementList) {
 o(getElementValue(element, elementName));
 s();
 }
 }
 }

private String getElementValue(Element element, String elementName) {
 return element.getChild(elementName).getValue();
 }

private void o(String out) {
 System.out.printf("%s\t%n", out);
 }

private void s() {
 System.out.printf("%n");
 }

@Before
 public void setUp() {
 jdomUtil = new JDomUtil();
 }

@After
 public void tearDown() {
 jdomUtil = null;
 }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s