title: Identifying the index of selected XML node from JTree
body: <p>I have a JTree where the input XML file is mapped into it. </p>
  
  <p><strong>library_system.xml</strong> </p>
  
  <pre><code>&lt;library&gt;
      &lt;user&gt;
          &lt;name&gt;Dinesh&lt;/name&gt;
          &lt;book&gt;
              &lt;info name="java"&gt;Java: The Complete Reference, 9th Edition&lt;/info&gt;
              &lt;info name="price"&gt;700&lt;/info&gt;
              &lt;details&gt;
                  &lt;parameter name="author"&gt;Herbert Schildt&lt;/parameter&gt;
                  &lt;parameter name="isbn"&gt;9339212096&lt;/parameter&gt;
                  &lt;parameter name="publisher"&gt;McGraw Hill Education&lt;/parameter&gt;
              &lt;/details&gt;
          &lt;/book&gt;
          &lt;book&gt;
              &lt;info name="java"&gt;Learning Python 3rd Edition&lt;/info&gt;
              &lt;info name="price"&gt;1020&lt;/info&gt;
              &lt;details&gt;
                  &lt;parameter name="author"&gt;Mark Lutz&lt;/parameter&gt;
                  &lt;parameter name="isbn"&gt;0596513984&lt;/parameter&gt;
                  &lt;parameter name="publisher"&gt;O'Reilly&lt;/parameter&gt;
              &lt;/details&gt;
          &lt;/book&gt;
      &lt;/user&gt;
      &lt;user&gt;
          &lt;name&gt;Vignesh&lt;/name&gt;
          &lt;book&gt;
              &lt;info name="java"&gt;Java: The Complete Reference, 9th Edition&lt;/info&gt;
              &lt;info name="price"&gt;700&lt;/info&gt;
              &lt;details&gt;
                  &lt;parameter name="author"&gt;Herbert Schildt&lt;/parameter&gt;
                  &lt;parameter name="isbn"&gt;9339212096&lt;/parameter&gt;
                  &lt;parameter name="publisher"&gt;McGraw Hill Education&lt;/parameter&gt;
              &lt;/details&gt;
          &lt;/book&gt;
      &lt;/user&gt;
  &lt;/library&gt;
  </code></pre>
  
  <p>When any node of XML selected from JTree, I am printing the selected node name and it's parent name. </p>
  
  <p><strong>StackOverFlow.java</strong></p>
  
  <pre><code>import java.awt.BorderLayout;
  import java.awt.Dimension;
  import java.awt.Toolkit;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import javax.swing.BorderFactory;
  import javax.swing.JButton;
  import javax.swing.JDialog;
  import javax.swing.JFrame;
  import javax.swing.JOptionPane;
  import javax.swing.JPanel;
  import javax.swing.JScrollPane;
  import javax.swing.JTree;
  import javax.swing.event.TreeSelectionEvent;
  import javax.swing.event.TreeSelectionListener;
  import javax.swing.tree.DefaultMutableTreeNode;
  import javax.swing.tree.TreeNode;
  import javax.swing.tree.TreePath;
  import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  
  /**
   *
   * @author dsivaji
   */
  public class StackOverFlow {
  
      public DefaultMutableTreeNode rootNode = null;//For writing
      public Element rootElement = null;
      private DocumentBuilder dBuilder = null;
      public Document doc = null;
      private String xmlFileName = null;
      public static DefaultMutableTreeNode lastNode = null;
      static String selctedXmlProperty = "";
      static String primaryCond = "";
      static Map&lt;String, List&gt; conditionsMap = new HashMap&lt;String, List&gt;();
  
  
      public StackOverFlow(String xmlFileName) {
  
          try {
              dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
              doc = dBuilder.newDocument();
  
              if (rootNode == null) {
                  rootElement = doc.createElement("devices");
                  doc.appendChild(rootElement);
                  rootNode = new DefaultMutableTreeNode(rootElement.getNodeName());
              }
              this.xmlFileName = xmlFileName;
          } catch (Exception e) {
              System.out.println("Exception in the XML document builders at the constructuor of XMLManipulator");
          }
      }
  
      static DefaultMutableTreeNode parseXML(String xmlFileName) {
  
          DefaultMutableTreeNode masterRootNode = null;
          DocumentBuilder dBuilder = null;
          Document doc = null;
  
          try {
              dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
              doc = dBuilder.newDocument();
              doc = dBuilder.parse(xmlFileName);
              if (doc.hasChildNodes()) {
                  masterRootNode = getXMLTree(doc.getChildNodes(), null);
              }
          } catch (Exception e) {
              System.out.println("Exception in XML parsing" + e);
              System.out.println("ex : " + e);
              masterRootNode = new DefaultMutableTreeNode("ERROR");
          }
  
          return masterRootNode;
      }
  
      private static DefaultMutableTreeNode getXMLTree(NodeList nodeList, DefaultMutableTreeNode treeParent) {
  
          //This will be assumed to be master one.
          DefaultMutableTreeNode rootParent = null;
  
          //If treeParent is null, then it called from the main, not a recursive one.
          if (treeParent == null) {
              rootParent = new DefaultMutableTreeNode("");
          } else {
              rootParent = treeParent;
          }
  
          for (int count = 0; count &lt; nodeList.getLength(); count++) {
  
              Node tempNode = nodeList.item(count);
  
              // make sure it's element node.
              if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
  
                  // get node name and value
                  String myNodeName = tempNode.getNodeName().toUpperCase();
  
                  DefaultMutableTreeNode parent = new DefaultMutableTreeNode(myNodeName);
                  lastNode = parent;
  //                System.out.println(tempNode.getNodeName() + " : " + tempNode.getNodeValue());
                  //If it has the attributes, then appending it with the parent text 
                  if (tempNode.hasAttributes()) {
  
                      // get attributes names and values
                      NamedNodeMap nodeMap = tempNode.getAttributes();
  
                      for (int i = 0; i &lt; nodeMap.getLength(); i++) {
  
                          Node node = nodeMap.item(i);
                          String nodeName = node.getNodeName();
                          if (nodeName.equals("name")) {
                              System.out.println("attr value : " + node.getNodeValue() + ", " + tempNode.getNodeValue());
  
                              parent.setUserObject(myNodeName + " (" + node.getNodeValue() + ")");
                          }
  //                        System.out.print("attr name : " + node.getNodeName());
  
                      }
                  } else {
  //                    System.out.println("Node Text content = " + tempNode.getTextContent());
                  }
  
                  //Adding it to the root parent of this current context
                  rootParent.add(parent);
  
                  if (tempNode.hasChildNodes()) {
                      // loop again if has child nodes and add it to the rootParent
                      rootParent.add(getXMLTree(tempNode.getChildNodes(), parent));
                  }
  //                System.out.println("Node Name = " + tempNode.getNodeName() + " [CLOSE]");
              } else if (tempNode.getNodeType() == Node.TEXT_NODE) {
                  String txtVal = tempNode.getNodeValue().trim();
                  if (!txtVal.isEmpty()) {
                      if (lastNode != null) {
                          lastNode.setUserObject(lastNode.getUserObject() + " = " + txtVal);
                      }
                      System.out.println("-&gt;" + txtVal + "&lt;-");
                  }
              }
          }
          return rootParent;
      }
  
      public void removeChilds(Node node) {
          while (node.hasChildNodes()) {
              node.removeChild(node.getFirstChild());
          }
      }
  
      public static void main(String[] args) {
          showGUI("C:\\library_system.xml");
      }
  
      public static void showGUI(final String logXmlFileName) {
          JFrame topoWindow = new JFrame("Library Info");
          topoWindow.setTitle(logXmlFileName.substring(logXmlFileName.lastIndexOf("\\") + 1));
          topoWindow.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  
          final JTree topoTree = new JTree(parseXML(logXmlFileName));
  
          topoTree.addTreeSelectionListener(new TreeSelectionListener() {
  
              public void valueChanged(TreeSelectionEvent e) {
                  JTree treeSource = (JTree) e.getSource();
                  TreePath tp = e.getNewLeadSelectionPath();
  
  //                System.out.println(Arrays.toString(e.getPaths()));
                  System.out.println(e.getPath());
  //                System.out.println(tp.getParentPath() + " at " + tp.getPathCount());
                  if (tp != null) {
  
                      TreeNode lastPathComponent = (TreeNode) tp.getLastPathComponent();
                      System.out.println(lastPathComponent.isLeaf());
                      System.out.println("parent -&gt; " + lastPathComponent.getParent().toString());
                      DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
                      System.out.println(node.getParent().getIndex(node));
  //                    System.out.println("parent -&gt;" + lastPathComponent.getParent().getParent().getChildCount());
                      selctedXmlProperty = tp.getLastPathComponent().toString();
                      System.out.println("val -&gt;" + tp.getLastPathComponent());
                  }
              }
          });
          final JScrollPane scrlTreeView = new JScrollPane(topoTree);
  
          final JPanel pnlLeft = new JPanel(new BorderLayout(5, 5));
  
          pnlLeft.add(scrlTreeView);
  
          topoWindow.add(pnlLeft);
  
          for (int i = 0; i &lt; topoTree.getRowCount(); i++) {
  //                System.out.println(topoTree.getPathForRow(i));
              topoTree.expandRow(i);
          }
  
          topoWindow.pack();
          topoWindow.setLocationRelativeTo(null);
          topoWindow.setSize(500, 500);
          topoWindow.setVisible(true);
      }
  }
  </code></pre>
  
  <p><strong>Output :</strong>
  <a href="https://i.stack.imgur.com/AC6AF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AC6AF.png" alt="enter image description here"></a></p>
  
  <pre><code>[, LIBRARY, USER, BOOK, DETAILS, PARAMETER (author) = Herbert Schildt]
  true
  parent -&gt; DETAILS
  0
  val -&gt;PARAMETER (author) = Herbert Schildt
  </code></pre>
  
  <p>The above messages are due to the following method</p>
  
  <pre><code>public void valueChanged(TreeSelectionEvent e) {
      JTree treeSource = (JTree) e.getSource();
      TreePath tp = e.getNewLeadSelectionPath();
      System.out.println(e.getPath());
      if (tp != null) {
          TreeNode lastPathComponent = (TreeNode) tp.getLastPathComponent();
          System.out.println(lastPathComponent.isLeaf());
          System.out.println("parent -&gt; " + lastPathComponent.getParent().toString());
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
          System.out.println(node.getParent().getIndex(node));
          selctedXmlProperty = tp.getLastPathComponent().toString();
          System.out.println("val -&gt;" + tp.getLastPathComponent());
      }
  }
  </code></pre>
  
  <p>Here, what should I do to know that a person has selected the 2nd <code>user</code> element's 1st <code>book</code> element's 1st <code>detail</code> element's attribute named <code>author</code> ?</p>