capint
11/30/2015 - 10:23 PM

Java >> XML >> DOM Parser

Java >> XML >> DOM Parser

FileInputStream fis = new FileInputStream(fileUriString);
DocumentBuilder docBuild;
docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//*** 1.Parse an FIS to a Document
Document c2b = docBuild.parse(fis);

//*** 2.Get element (node) by tag name
Node root = c2b.getElementsByTagName("c2b").item(0);

//*** 3.getNamedItem <=> Retrieve a node by name
title = root.getAttributes().getNamedItem("title").getNodeValue();
author = root.getAttributes().getNamedItem("author").getNodeValue();
level = root.getAttributes().getNamedItem("level").getNodeValue();
media = root.getAttributes().getNamedItem("media").getNodeValue();

//*** 2.Get elements (NodeList) by tag name
NodeList beats = c2b.getElementsByTagName("beat");
targets = new ArrayList<Target>();
for (int i = 0; i < beats.getLength(); i++) {
  NamedNodeMap attribs = beats.item(i).getAttributes();
  double time = Double.parseDouble(attribs.getNamedItem("time").getNodeValue());
  int x = Integer.parseInt(attribs.getNamedItem("x").getNodeValue());
  int y = Integer.parseInt(attribs.getNamedItem("y").getNodeValue());
  String colorStr = attribs.getNamedItem("color").getNodeValue();
  targets.add(new Target(time, x, y, colorStr));
}