Skip to content

Instantly share code, notes, and snippets.

@timothyshort
Created July 26, 2017 12:40
Show Gist options
  • Save timothyshort/5abf0be8cd2b042d0bb37444ca89b0a4 to your computer and use it in GitHub Desktop.
Save timothyshort/5abf0be8cd2b042d0bb37444ca89b0a4 to your computer and use it in GitHub Desktop.
This function takes an XML file and returns the data as a double array
// Dependencies: javax.xml | org.w3c.com | org.xml.sax
public static String[][] get(String file) {
String[][] data = null;
// 1. Prepare Xpath
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
try {
// 2. Create XML File
InputSource xmlFile = new InputSource(file);
// 3. Node Settings
// Parent Node
NodeList cars = (NodeList) xPath.evaluate("/cars/car", xmlFile, XPathConstants.NODESET);
// Child Nodes
XPathExpression xBodyStyle = xPath.compile("bodyStyle");
// 4. Define the array : columns (fields) must be known and set manually
int rows = cars.getLength();
int columns = 4;
data = new String[rows][columns];
// 4. Iterate Through XML Based on Parent Node
for(int i=0; i<cars.getLength(); i++) {
// Create a Node for each record
Node carRecord = cars.item(i);
// Capture Data for Each Record and Store in Variables
String carType = carRecord.getAttributes().item(0).getTextContent();
String bodyStyle = xBodyStyle.evaluate(carRecord, XPathConstants.STRING).toString();
// Place into Array
data[i][0] = carType;
data[i][1] = bodyStyle;
}
} catch (XPathExpressionException e) {
System.out.println("ERROR READING XML FILE");
e.toString();
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment