public void startElement(String uri, String localName, String qName, Attributes atts)
      throws SAXException {
    SwingTreeNodeImpl<String> newNode = new SwingTreeNodeImpl<String>();

    if (currentNode == null) {
      rootNodes.add(newNode);
    } else {
      currentNode.addChild(newNode);
    }

    newNode.setData(JOINER.join(newNode.getData(), localName.toLowerCase(Locale.US), " ["));

    currentNode = newNode;
  }
 public void endElement(String uri, String localName, String qName) throws SAXException {
   currentNode.setData(JOINER.join(currentNode.getData(), "]"));
   currentNode = (SwingTreeNodeImpl) currentNode.getParent();
 }
/** @author Nick Belaevski */
public class TreeNodeParser implements ContentHandler {
  private static final FastJoiner JOINER = FastJoiner.on("");
  private XMLReader reader;
  private List<TreeNode> rootNodes = Lists.newArrayList();
  private SwingTreeNodeImpl<String> currentNode;

  public TreeNodeParser() throws SAXException {
    reader = XMLReaderFactory.createXMLReader();
  }

  public void parse(URL url) throws IOException, SAXException {
    InputStream is = null;
    try {
      is = url.openStream();
      reader.setContentHandler(this);
      reader.parse(new InputSource(is));
    } finally {
      Closeables.closeQuietly(is);
    }
  }

  public List<TreeNode> getRootNodes() {
    return rootNodes;
  }

  public void setDocumentLocator(Locator locator) {}

  public void startDocument() throws SAXException {}

  public void endDocument() throws SAXException {}

  public void startPrefixMapping(String prefix, String uri) throws SAXException {}

  public void endPrefixMapping(String prefix) throws SAXException {}

  public void startElement(String uri, String localName, String qName, Attributes atts)
      throws SAXException {
    SwingTreeNodeImpl<String> newNode = new SwingTreeNodeImpl<String>();

    if (currentNode == null) {
      rootNodes.add(newNode);
    } else {
      currentNode.addChild(newNode);
    }

    newNode.setData(JOINER.join(newNode.getData(), localName.toLowerCase(Locale.US), " ["));

    currentNode = newNode;
  }

  public void endElement(String uri, String localName, String qName) throws SAXException {
    currentNode.setData(JOINER.join(currentNode.getData(), "]"));
    currentNode = (SwingTreeNodeImpl) currentNode.getParent();
  }

  public void characters(char[] ch, int start, int length) throws SAXException {
    currentNode.setData(JOINER.join(currentNode.getData(), new String(ch, start, length).trim()));
  }

  public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}

  public void processingInstruction(String target, String data) throws SAXException {}

  public void skippedEntity(String name) throws SAXException {}
}
 public void characters(char[] ch, int start, int length) throws SAXException {
   currentNode.setData(JOINER.join(currentNode.getData(), new String(ch, start, length).trim()));
 }