Hi,
I have a JTree structure based on dynamic xml document. This takes a DOM Node and recurses through the children until each one is added to a DefaultMutableTreeNode. The JTree then uses this object as a tree model.
The problem I am facing is how to extract the specific attribute value.
For example:
<item item_id="1" item_title="Favorites" item_dsc="My Favorites" >
<item_service item_service_usr_svc_nam="News"/>
</item>
The item element have three attributes.
When I go though the nodes, I just want to display the the value of item_desc.
The result I will get will be "Favorites". any ideas? Thanks.
--Zoe
---here is the short src codes; it displays all attributes.
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class XTree extends JTree
{
private DefaultMutableTreeNode treeNode;
private DocumentBuilderFactory dbf;
private DocumentBuilder db;
private Document
doc;
public XTree(
String text ) throws ParserConfigurationException
{
super();
getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
setShowsRootHandles( true );
setEditable( false ); // A more advanced version of this tool would allow the Tree to be editable
// Begin by initializing the object's DOM parsing objects
dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating( false );
db = dbf.newDocumentBuilder();
// Take the DOM root node and convert it to a Tree model for the JTree
treeNode = createTreeNode( parseXml( text ) );
setModel( new DefaultTreeModel( treeNode ) );
}
/**
* This takes a DOM Node and recurses through the children until each one is added
* to a DefaultMutableTreeNode. The JTree then uses this object as a tree model.
*/
private DefaultMutableTreeNode createTreeNode( Node root )
{
DefaultMutableTreeNode treeNode = null;
String type, name, value;
NamedNodeMap attribs;
Node attribNode;
// Get data from root node
type = getNodeType( root );
name = root.getNodeName();
value = root.getNodeValue();
// Special case for TEXT_NODE
treeNode = new DefaultMutableTreeNode( root.getNodeType() == Node.TEXT_NODE ? value : name );
// Display the attributes if there are any
attribs = root.getAttributes();
if( attribs != null )
{
for( int i = 0; i < attribs.getLength(); i++ )
{
attribNode = attribs.item(i);
name = attribNode.getNodeName().trim();
value = attribNode.getNodeValue().trim();
if( value != null )
{
if( value.length() > 0 )
{
treeNode.add( new DefaultMutableTreeNode( "[Attribute] --> " + name + "=\"" + value + "\"" ) );
..............