Skip to content

Some useful XML manipulations in JAVA

July 11, 2013

private static String ROOT_NODE_NAME = “dataset”;
private static String ROW_NODE_NAME = “row”;

public static String resultSetToXML(ResultSet rs) {
String result = null;

try {
org.jdom.Document root = new org.jdom.Document(new org.jdom.Element(ROOT_NODE_NAME));
ResultSetMetaData metaData = rs.getMetaData();

// Get all rows.
while (rs.next()) {
org.jdom.Element row = new org.jdom.Element(ROW_NODE_NAME);
// Add to root
root.getRootElement().addContent(row);

for (int i = 1; i <= metaData.getColumnCount(); i++) {
if(metaData.getColumnLabel(i).trim().equals(“”)){
continue;
}
// Use the column label as the node name
org.jdom.Element val = new org.jdom.Element(metaData.getColumnLabel(i));
// Use the String value of the data as the value node’s child
val.setText(“” + rs.getObject(i));
row.addContent(val);
}
}

XMLOutputter out = new XMLOutputter();
out.setFormat(Format.getPrettyFormat());
result = out.outputString(root);
} catch (Exception e) {
e.printStackTrace();
}

return result;
}

private static String RESULT_NODE_NAME = “result”;
public static String combineXMLs(List<String> inputXMLs) {
String result = “”;

try {
org.jdom.Document root = new org.jdom.Document(
new org.jdom.Element(“results”));
int resultset_count = 0;
for (String xml : inputXMLs) {
resultset_count++;
SAXBuilder builder = new SAXBuilder();
org.jdom.Document document = builder
.build(new ByteArrayInputStream(xml.getBytes()));

org.jdom.Element resultset = new org.jdom.Element(RESULT_NODE_NAME + “_” +resultset_count);
org.jdom.Element singleXmlContent = document.detachRootElement();
resultset.addContent(singleXmlContent);
root.getRootElement().addContent(resultset);
}
XMLOutputter out = new XMLOutputter();
out.setFormat(Format.getPrettyFormat());
result = out.outputString(root);
} catch (Exception e) {
e.printStackTrace();
}

return result;
}

public static String removeTags(String input, List<String> ignoreList) {
String regex_template = “\\<[tag]\\>.*?\\</[tag]\\>”;
String output = input;

for (String tag : ignoreList){
String regex = regex_template.replace(“[tag]”, tag);
output = output.replaceAll(regex, “”);
}
output = output.replaceAll(“(?m)^[ \t]*\r?\n”, “”);
return output;
}

From → Interests

Leave a Comment

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

%d bloggers like this: