Reputation: 19905
Is there a "standardized" way (i.e., code pattern, or, even better, open source library) in Java for dynamically flattening ("shredding") a hierarchical XML file, of large size and unknown structure, with output not redirected to an RDBMS but directly accessible?
I am looking at a transformation like the one mentioned in this question, but all the code examples I have seen use some SQL command to inject the flattened XML input to a database table, via an RDBMS (e.g., MySQL).
What I would like to do is progressively extract the XML data into a string, or, at least, into a text file, which could be post-processed afterwards, without going through any RDBMS.
EDIT:
After working further on the issue, there are a couple of solutions using XSLT (including a fully parameterizable one) in this question.
Upvotes: 1
Views: 714
Reputation: 1193
You could do it with JDOM (see example below, jdom.jar has to be on the classpath). But beware, the whole dom is in memory. If the XML is bigger you should use XSLT or a SAX parser.
import java.io.IOException;
import java.io.StringReader;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.junit.Test;
public class JDomFlatten {
@Test
public void testFlatten() {
final String xml = "<grandparent name=\"grandpa bob\">"//
+ "<parent name=\"papa john\">"//
+ "<children>"//
+ "<child name=\"mark\" />"//
+ "<child name=\"cindy\" />"//
+ "</children>"//
+ "</parent>"//
+ "<parent name=\"papa henry\">"//
+ "<children>" //
+ "<child name=\"mary\" />"//
+ "</children>"//
+ "</parent>" //
+ "</grandparent>";
final StringReader stringReader = new StringReader(xml);
final SAXBuilder builder = new SAXBuilder();
try {
final Document document = builder.build(stringReader);
final Element grandparentElement = document.getRootElement();
final StringBuilder outString = new StringBuilder();
for (final Object parentElementObject : grandparentElement.getChildren()) {
final Element parentElement = (Element) parentElementObject;
for (final Object childrenElementObject : parentElement.getChildren()) {
final Element childrenElement = (Element) childrenElementObject;
for (final Object childElementObject : childrenElement.getChildren()) {
final Element childElement = (Element) childElementObject;
outString.append(grandparentElement.getAttributeValue("name"));
outString.append(" ");
outString.append(parentElement.getAttributeValue("name"));
outString.append(" ");
outString.append(childElement.getAttributeValue("name"));
outString.append("\n");
}
}
}
System.out.println(outString);
} catch (final JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Upvotes: 2