Creating an XML Tree

www.altova.com Imprimir este apartado Página anterior Subir un nivel Página siguiente

Inicio >  Referencia del programador > ActiveX Integration > ActiveX Integration Examples > Java >

Creating an XML Tree

The listing below loads an XML data object as nodes in a tree.

 

 

01 // access required XMLSpy Java-COM classes

02 import com.altova.automation.XMLSpy.XMLData;

03

04 // access AWT and Swing components

05 import java.awt.*;

06 import javax.swing.*;

07 import javax.swing.tree.*;

08

09 /**

10  * A simple example of a tree control loading the structure from an XMLData object.

11  * The class receives an XMLData object, loads its nodes in a JTree, and prepares

12  * for modal activation.

13  *

14  * Feel free to modify and extend this sample.

15  *

16  * @author Altova GmbH

17  */

18 class XMLTreeDialog extends JDialog

19 {

20   /**

21    * The tree control

22    */

23   private JTree myTree;

24  

25   /**

26    * Root node of the tree control

27    */

28   private DefaultMutableTreeNode top ;

29

30   /**

31    * Constructor that prepares the modal dialog containing the filled tree control

32    * @param xml   The data to be displayed in the tree

33    * @param parent  Parent frame

34    */

35   public XMLTreeDialog( XMLData xml, Frame parent )

36   {

37     // Construct the modal dialog

38     super( parent, "XML tree", true );

39     // Arrange controls in the dialog

40     top = new DefaultMutableTreeNode("root");    

41     myTree = new JTree(top);

42     setContentPane( new JScrollPane( myTree ) );

43     // Build up the tree

44     fillTree( top, xml );

45     myTree.expandRow( 0 );

46   }

47

48   /**

49    * Loads the nodes of an XML element under a given tree node

50    * @param node  Target tree node

51    * @param elem  Source XML element

52    */

53   private void fillTree( DefaultMutableTreeNode node, XMLData elem)

54   {

55     try

56     {

57       // There are several ways to iterate through child elements: either using the getFirstChild/getNextChild,

58       // or by incrementing an index up to countChildren and calling getChild [as shown below].

59       // If you only want to get children of one kind, you should use countChildrenKind/getChildKind,

60       // or provide a kind to the getFirstChild before iterating with the getNextChild.

61       int nSize = elem.countChildren() ;

62       for ( int i = 0 ; i < nSize ; ++i)

63       {

64         // Create a new tree node for each child element, and continue recursively

65         XMLData newElem = elem.getChild(i) ;

66         DefaultMutableTreeNode newNode = new DefaultMutableTreeNode( newElem.getName() ) ;

67         node.add( newNode ) ;

68         fillTree( newNode, newElem ) ;

69       }

70     }

71     catch (Exception e)

72     {

73       e.printStackTrace();

74     }

75   }

76

77 }

 

 


© 2019 Altova GmbH