Chương trình java sau đây ứng dụng mô hình DOM để duyệt qua 1 văn bản XML sau đó hiển thị lên JTree.
Trong đó lớp MyNode.java có nội dung sau
package dom.swing;
import java.util.ArrayList;
public class MyNode {
private String nodeID;//ID
private String nodeValue;//giá trị vủa node
private ArrayListattributes;//lưu giữ các thuộc tính của node
public String getNodeID() {
return nodeID;
}
public void setNodeID(String nodeID) {
this.nodeID = nodeID;
}
public String getNodeValue() {
return nodeValue;
}
public void setNodeValue(String nodeValue) {
this.nodeValue = nodeValue;
}
public ArrayList<String> getAttributes() {
return attributes;
}
public void setAttributes(ArrayList<String> attributes) {
this.attributes = attributes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final MyNode other = (MyNode) obj;
if (nodeID == null) {
if (other.nodeID != null)
return false;
} else if (!nodeID.equals(other.nodeID))
return false;
return true;
}
public MyNode(String nodeID, String nodeValue, ArrayList attributes) {
super();
this.nodeID = nodeID;
this.nodeValue = nodeValue;
this.attributes = attributes;
}
public MyNode() {
super();
}
@Override
public String toString() {
return this.nodeID;
}
}
Kết quả thu được như hình sau
package dom.swing; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class ParseTree extends JFrame implements TreeSelectionListener, ActionListener{ private static final long serialVersionUID = 1L; private DefaultMutableTreeNode root; private DefaultTreeModel model; private JTree tree; private JTextArea taContent; private JMenuBar menubar; private JMenu menuFile; private JMenuItem itemOpen,itemExit; public ParseTree(){ super(“Parser Tree”); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(700,500); menubar=new JMenuBar(); menuFile=new JMenu(“File”); itemOpen=new JMenuItem(“Open”);itemExit=new JMenuItem(“Exit”); this.setJMenuBar(menubar); menubar.add(menuFile); menuFile.add(itemOpen);menuFile.addSeparator(); menuFile.add(itemExit); itemOpen.addActionListener(this); itemExit.addActionListener(this); root=new DefaultMutableTreeNode(“XML Document”); model=new DefaultTreeModel(root); tree=new JTree(model); tree.addTreeSelectionListener(this); taContent=new JTextArea(); taContent.setEditable(false); JScrollPane xxx=new JScrollPane(taContent); JScrollPane sp=new JScrollPane(tree); sp.setPreferredSize(new Dimension(300,300)); JSplitPane spl=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,sp,xxx); this.add(spl,BorderLayout.CENTER); } void buildtree(String uri){ try { DOMParser parser=new DOMParser(); parser.parse(uri); Document doc=parser.getDocument(); addNode(doc,root); } catch (Exception e) { e.printStackTrace(); } } void addNode(Node xmlNode,DefaultMutableTreeNode treeNode){ if(xmlNode==null) return; int type=xmlNode.getNodeType(); MyNode mn=null; switch (type) { case Node.DOCUMENT_NODE:{ mn=new MyNode(“xml”,“”,null); DefaultMutableTreeNode tn=new DefaultMutableTreeNode(mn); root.add(tn); addNode(((Document)xmlNode).getDocumentElement(), treeNode); break; } case Node.ELEMENT_NODE:{ mn=new MyNode(xmlNode.getNodeName(),xmlNode.getNodeValue(),null); int length=(xmlNode.getAttributes()!=null)?xmlNode.getAttributes().getLength():0; ArrayList<String>al=new ArrayList<String>(); Attr []attributes=new Attr[length]; for (int i = 0; i < length; i++) { attributes[i]=(Attr)xmlNode.getAttributes().item(i); } String text=“”; for (int i = 0; i < attributes.length; i++) { Attr attribute=attributes[i]; text=attribute.getNodeName()+“@”+ attribute.getNodeValue(); al.add(text);//dưa vào danh sách các thuộc tính } mn.setAttributes(al);//cap nhật DefaultMutableTreeNode tn=new DefaultMutableTreeNode(mn); treeNode.add(tn); NodeList childNodes=xmlNode.getChildNodes(); if(childNodes!=null){ length=childNodes.getLength(); for (int i = 0; i < length; i++) { addNode(childNodes.item(i), tn); } } break; } case Node.CDATA_SECTION_NODE:{ String x=“<!--[CDATA["+ xmlNode.getNodeValue()+ "]]>”; mn.setNodeValue(x); break; } case Node.TEXT_NODE:{ String newText=xmlNode.getNodeValue().trim(); ((MyNode)treeNode.getUserObject()).setNodeValue(newText); break; } case Node.PROCESSING_INSTRUCTION_NODE:{ String text=xmlNode.getNodeValue(); ((MyNode)treeNode.getUserObject()).setNodeValue(text); break; } } } /** * @param args */ public static void main(String[] args) { new ParseTree().setVisible(true); } @Override public void valueChanged(TreeSelectionEvent e) { try { DefaultMutableTreeNode selNode=(DefaultMutableTreeNode)e.getPath().getLastPathComponent(); Object obj=selNode.getUserObject(); if (obj instanceof MyNode) { MyNode node=(MyNode)obj; String text=node.getNodeID()+“:”+node.getNodeValue(); if(node.getAttributes()!=null&&node.getAttributes().size()>0) text+=“\n”+node.getAttributes().toString(); taContent.setText(text); } else taContent.setText(obj.toString()); } catch (Exception e1) { e1.printStackTrace(); } } @Override public void actionPerformed(ActionEvent e) { Object o=e.getSource(); if(o.equals(itemOpen)){ JFileChooser fc=new JFileChooser(); if(fc.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){ String uri=fc.getSelectedFile().getAbsolutePath(); buildtree(uri); tree.expandRow(0); } } else if(o.equals(itemExit)){ System.exit(1); } } } |
Trong đó lớp MyNode.java có nội dung sau
package dom.swing;
import java.util.ArrayList;
public class MyNode {
private String nodeID;//ID
private String nodeValue;//giá trị vủa node
private ArrayListattributes;//lưu giữ các thuộc tính của node
public String getNodeID() {
return nodeID;
}
public void setNodeID(String nodeID) {
this.nodeID = nodeID;
}
public String getNodeValue() {
return nodeValue;
}
public void setNodeValue(String nodeValue) {
this.nodeValue = nodeValue;
}
public ArrayList<String> getAttributes() {
return attributes;
}
public void setAttributes(ArrayList<String> attributes) {
this.attributes = attributes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final MyNode other = (MyNode) obj;
if (nodeID == null) {
if (other.nodeID != null)
return false;
} else if (!nodeID.equals(other.nodeID))
return false;
return true;
}
public MyNode(String nodeID, String nodeValue, ArrayList attributes) {
super();
this.nodeID = nodeID;
this.nodeValue = nodeValue;
this.attributes = attributes;
}
public MyNode() {
super();
}
@Override
public String toString() {
return this.nodeID;
}
}
Kết quả thu được như hình sau
إرسال تعليق